I want to create a JavaScript wait()
function.
What should I edit?
function wait(waitsecs) {
setTimeout(donothing(), 'waitsecs');
}
function donothing() {
//
}
Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).
To specifically address your problem, you should remove the brackets after donothing
in your setTimeout
call, and make waitsecs
a number not a string:
console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');
But that won't stop execution; "after" will be logged before your function runs.
To wait properly, you can use anonymous functions:
console.log('before');
setTimeout(function(){
console.log('after');
},500);
All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval
/ clearInterval
if it needs to loop.