I want to create a JavaScript wait()
function.
What should I edit?
function wait(waitsecs) { setTimeout(donothing(), 'waitsecs'); } function donothing() { // }
JavaScript code execution is asynchronous by default, which means that JavaScript won't wait for a function to finish before executing the code below it.
Unfortunately, there is no sleep function like that in JavaScript . If you run test2, you will see 'hi' right away ( setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.
Sleep() With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and Php we would call sleep(sec).
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.
You shouldn't edit it, you should completely scrap it.
Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout
correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With