286

Is there a sleep function in JavaScript?

Yi Jiang's user avatar
Yi Jiang
50.2k16 gold badges139 silver badges137 bronze badges
askedJul 17, 2009 at 3:16
user120324's user avatar
3
  • 8
    The modern practice is to simply useawait sleep(<duration>).CommentedOct 7, 2016 at 10:30
  • 1
    please have a look at this answerstackoverflow.com/a/39914235/7219400CommentedJan 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));CommentedAug 23, 2023 at 15:58

4 Answers4

398

If you are looking to block the execution of code with call tosleep, then no, there is no method for that inJavaScript.

JavaScript does havesetTimeout method.setTimeout will let youdefer 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 howsleep 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 nosleep function like that inJavaScript.

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

Vaidas's user avatar
Vaidas
1,02810 silver badges23 bronze badges
answeredJul 17, 2009 at 3:35
SolutionYogi's user avatar
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 useawait 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 newsettimeout .
@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);}
Lee Goddard's user avatar
Lee Goddard
11.3k5 gold badges53 silver badges71 bronze badges
answeredMar 17, 2012 at 9:03
Reema's user avatar

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 wasnot "What is best practice executing something with a delay?"
|
94

You can use thesetTimeout orsetInterval functions.

Ionuț G. Stan's user avatar
Ionuț G. Stan
180k19 gold badges196 silver badges206 bronze badges
answeredJul 17, 2009 at 3:18
Andromeda's user avatar

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 toawait on a promise withsetTimeout():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.

answeredDec 7, 2012 at 6:42
Shalab's user avatar

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.