Is there a sleep function in JavaScript?
4 Answers
If you are looking to block the execution of code with call to sleep
, then no, there is no method for that in JavaScript
.
JavaScript
does have setTimeout
method. setTimeout
will let you defer execution of a function for x milliseconds.
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
Remember, this is completely different from how sleep
method, if it existed, would behave.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
If you run the above function, you will have to wait for 3 seconds (sleep
method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep
function like that in JavaScript
.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
If you run test2, you will see 'hi' right away (setTimeout
is non blocking) and after 3 seconds you will see the alert 'hello'.
-
7Would add a couple of further points. The function assigned to the setTimeout is put onto an event queue. JavaScript is inherently single-threaded. If there’s at least one event on the queue that’s eligible to “fire” (like a 3000ms timeout that was set 4000ms ago), the "javascript VM" will pick one and call its handler (function callback). The point is that the actual call will unlikely be precisely when you requested it (say 3000 milliseconds later), it might be 3001, 3002 or even quite a bit later depending on number and nature of other events on the queue, & the duration of their callbacks. May 31, 2014 at 0:49
-
2
-
Thanks. I used this in an aspx page that was redirecting to another page using JavaScript, to pause 3 seconds before redirection so that the console.log message would stay visible in the browser web developer tools: context.Response.Write("<script language='javascript'>setTimeout(function(){self.location='/401.aspx';},3000); console.log('Site is Redirecting');</script>"); Jan 14, 2020 at 20:08
-
1@DanDascalescu Why is your comment not an answer?
await sleep
seems the newsettimeout
.– TimoApr 18 at 9:56 -
1
A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
-
169This is an incredibly bad idea. Please for goodness sake do not use this code.– Yi JiangMar 17, 2012 at 11:57
-
9That wastes battery, and blocks JS from executing in the whole page. A very bad idea. Mar 17, 2012 at 12:08
-
20@TomWijsman Actually, this is a real, nicely blocking sleep;) I see no reason to use this, but it's a better sleep than setTimeout or setInterval, since they don't block execution like sleep does. May 2, 2012 at 10:31
-
8Pity it will trigger a cpu race 'till it returns, but for short sleeps that isn't too big a deal, bigger pity is that javascript doesn't provide this in a non-cpu intensive fashion.– PerkinsApr 15, 2013 at 0:27
-
87The JS is not wrong, it does exactly what was asked. If you were to say it is poor practice for production, then that would be valid, but being flippant and adversarial is just the way some people have to be I guess. This is very useful for certain debugging and testing scenarios and actually answers the question that was asked. The question was not "What is best practice executing something with a delay?"– AaronLSNov 13, 2013 at 20:37
You can use the setTimeout
or setInterval
functions.
-
77Sleep is synchronous, and setTimeout is asynchronous though so there could be some confusion with haphazardly using those implementations. Feb 28, 2016 at 5:47
-
2There could be confusion, but it is rare that someone wants to actually block all computation in the entire program. For beginners, the question is usually "how do I pause this one individual function for a bit?" in my experience, so the answer is to
await
on a promise withsetTimeout()
: masteringjs.io/tutorials/fundamentals/sleep Oct 15, 2019 at 14:40
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.
-
1
-
1
-
10Also do not do while(1) {}. Another very bad idea. I have a lot of very bad ideas which I will happily share upon request. Aug 31, 2017 at 17:52
-
1
-
4
await sleep(<duration>)
.