Is there a simple way to pause the script in Javascript? I'm looking for the javascript equivalent of time.sleep(1)
in Python. I do NOT want setTimeout(continueExecution, 10)
, or anything with getTime
. Can this be done?
EDIT: It wasn't quite as easy, but I think I can get it done with setTimeout
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'.
Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.
Unlike Java or Python, Javascript does not have a built-in sleep function. So, how might you be able to implement a method with the same functionality as the sleep function? A simple way to create a delay in Javascript is to use the setTimeout method.
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
JavaScript is usually ran in a single thread using an event-loop. This is why you can't do any "Thread.sleep". If you could it would freeze everything else for that duration and believe me you don't want to do that. This is why almost everything in JavaScript runs using non-blocking IO and that's why the only way you can do delay execution is by using setTimeout or setInterval.
without setTimeout, you could always loop until you reach a desired date time:
Disclaimers: This is untested. Since javascript is single-threaded, this WILL freeze your entire browser while looping. See other questions for more information on this topic.
var delay = 5; // 5 second delay
var now = new Date();
var desiredTime = new Date().setSeconds(now.getSeconds() + delay);
while (now < desiredTime) {
now = new Date(); // update the current time
}
// continue execution
If you are using jQuery 1.5+ you can make a really simple plugin (i
(function($) {
$.wait = function(time) {
return $.Deferred(function(dfd) {
setTimeout(dfd.resolve, time); // use setTimeout internally.
}).promise();
}
}(jQuery));
Then use it like this:
$.wait(3000).then(function(){
....
});
And it will launch your function after waiting 3 seconds. It use setTimeout internally, but that's the only way to do it in JavaScript.
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