286

Is there a sleep function in JavaScript?

3
  • 8
    The modern practice is to simply use await sleep(<duration>). Commented Oct 7, 2016 at 10:30
  • 1
    please have a look at this answer stackoverflow.com/a/39914235/7219400 Commented Jan 31, 2022 at 19:10
  • 2
    The answers are not good, the simplest and best answer is: function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } and you can use this like: await new Promise(r => setTimeout(r, 2000)); Commented Aug 23, 2023 at 15:58

4 Answers 4

398

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'.

Sign up to request clarification or add additional context in comments.

5 Comments

Would 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.
In the meantime you can simply use await sleep(3000).
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>");
@DanDascalescu Why is your comment not an answer? await sleep seems the new settimeout .
@Timo: have you clicked the link in my comment?
108

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); } 

21 Comments

This is an incredibly bad idea. Please for goodness sake do not use this code.
That wastes battery, and blocks JS from executing in the whole page. A very bad idea.
@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.
Pity 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.
The 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?"
|
94

You can use the setTimeout or setInterval functions.

2 Comments

Sleep is synchronous, and setTimeout is asynchronous though so there could be some confusion with haphazardly using those implementations.
There 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 with setTimeout(): masteringjs.io/tutorials/fundamentals/sleep
48
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.

9 Comments

Is the delay in seconds or milliseconds? Thanks.
It's in milliseconds.
Also do not do while(1) {}. Another very bad idea. I have a lot of very bad ideas which I will happily share upon request.
I think you mean this code IS blocking.
hahahaha for the last sentence to this answer
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.