Delay/sleep In Javascript?
Solution 1:
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.
Solution 2:
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 delayvar now = newDate();
var desiredTime = newDate().setSeconds(now.getSeconds() + delay);
while (now < desiredTime) {
now = newDate(); // update the current time
}
// continue execution
Solution 3:
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.
Solution 4:
You can use this code: (stolen from http://www.phpied.com/sleep-in-javascript/)
functionsleep(milliseconds) {
var start = newDate().getTime();
for (var i = 0; i < 1e7; i++) {
if ((newDate().getTime() - start) > milliseconds){
break;
}
}
}
This will actually block the script execution for however many milliseconds you desire. Don't use it unless you are trying to simulate a task that takes a long time, or something like that.
Solution 5:
we have a npm package called sleep that you can see it here
and for using it simply
var sleep = require('sleep');
sleep.sleep(10) //sleep for 10 seconds
but pay attention to this
These calls will block execution of all JavaScript by halting Node.js' event loop!
if you want sleep with promise you can use then-sleep npm package that is a good choice
var sleep = require('then-sleep');
// Sleep for1 second anddo something then.
sleep(1000).then(...);
also if you use ES7
you can use es7-sleep npm package
Post a Comment for "Delay/sleep In Javascript?"