Is there a sleep function in JavaScript?
-
8The modern practice is to simply use [`await sleep(
)`](http://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/39914235#39914235). – Dan Dascalescu Oct 07 '16 at 10:30 -
please have a look at this answer https://stackoverflow.com/a/39914235/7219400 – Sahin Jan 31 '22 at 19:10
-
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));` – Sahin Aug 23 '23 at 15:58
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'.

- 968
- 9
- 22

- 31,807
- 12
- 70
- 78
-
8Would 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. – arcseldon May 31 '14 at 00:49
-
2In the meantime you can simply use [`await sleep(3000)`](http://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/39914235#39914235). – Dan Dascalescu Oct 07 '16 at 10:29
-
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(""); – Michael Russ Jan 14 '20 at 20:08
-
1@DanDascalescu Why is your comment not an answer? `await sleep` seems the new `settimeout` . – Timo Apr 18 '22 at 09: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);
}

- 10,680
- 4
- 46
- 63

- 1,651
- 1
- 10
- 2
-
204This is an incredibly bad idea. Please for goodness sake do not use this code. – Yi Jiang Mar 17 '12 at 11:57
-
12That wastes battery, and blocks JS from executing in the whole page. A very bad idea. – CodesInChaos Mar 17 '12 at 12:08
-
1
-
23@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. – Christoph May 02 '12 at 10:31
-
10Pity 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. – Perkins Apr 15 '13 at 00:27
-
107The 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?" – AaronLS Nov 13 '13 at 20:37
-
4Finally someone who can write out how to use the sleep function (not a fancy setTimeout function). I don't really care if it's bad practice if I only want to debug something for a second. – CorayThan Jan 04 '14 at 00:45
-
1@AaronLS This isn't just "poor practice", this is **incredibly bad** and not even useful for debugging - it locks up the browser and makes it unusable until the loop is over! Even trying to figure out a race condition (by "slowing down" one callback) won't work right because javascript is single-threaded - _all_ execution is paused, not just the current callback! – Izkata Jan 13 '14 at 19:23
-
8@Izkata "poor practice"=="incredibly bad" semantically as far as I am concerned. You haven't said anything anyone else hasn't already said. All the things you've said are important information that are appropriate to include as comments, but none of them make the answer incorrect. The code is correct. It operates as expected. Yes the expected behavior is undesirable, but it still operates as expected, therefore the code, while being bad practice, is correct. It doesn't deserve a downvote in the context of the question being asked. – AaronLS Jan 13 '14 at 22:43
-
2@Izkata And sometimes it is useful for debugging to pause the entire browser process. There is alot more to requests and a web stack than just the client browser. – AaronLS Jan 13 '14 at 22:45
-
1@Izkata If you want to start a question regarding best practice alternatives to sleep, then go for it. It will probably be closed because it will encourage subjective answers. This is not that question. – AaronLS Jan 13 '14 at 22:48
-
-
1Who says it locks up the browser? That assumes it is being called in the rendering thread (true, in the example above it *is* in the rendering thread), a blocking sleep function inside a web worker would not cause any issues... Pity that it spikes the CPU, but that may not be a critical problem for some use cases. – Perkins Apr 16 '15 at 18:43
-
1
-
1That's called "Busy waiting". Using that name you can research more about pros and cons of doing that. – Mauro Gagna Aug 17 '16 at 22:36
-
1For the delay part, this is a little cleaner.... var end = new Date().getTime()+ delay; while (new Date().getTime() < end); – xtempore Sep 24 '17 at 10:38
-
1This is very useful for debugging latency on WebSockets. Currently there are no tools to simulate that, thanks! – adelriosantiago Jan 31 '18 at 03:57
-
@AaronLS no, it doesn't answer the question. Sleep() doesn't keep the thread busy. – Yola Feb 18 '22 at 20:55
-
@Yola Where is that requirement defined in the question? Also, why are you addressing that to me? I didn't post this answer. Additionally, most implementations of sleep in other languages are synchronous. So I'm not sure what you're using as your litmus test for your claim. – AaronLS Feb 18 '22 at 21:43
-
@AaronLS because you said that this answers the question. Yes, they are synchronous but they release resources. But true that question has not enough clarity. – Yola Feb 18 '22 at 22:54
-
It's never recommended to write improvised code, e.g: do not use ```while``` when you can use a ```setTimeout``` – DIIMIIM May 06 '22 at 09:14
-
Upvoting this ... I see people saying that this is a bad idea (or even an "incredibly bad idea") - no it isn't, it depends on what you want to do ... this function is useful for debugging purposes, but it is indeed not to be used in a production app to produce a "delay" (yes, we all know about JS's event loop, unless we're completely new to JS). – leo Jun 25 '22 at 09:33
You can use the setTimeout
or setInterval
functions.

- 176,118
- 18
- 189
- 202

- 12,659
- 20
- 77
- 103
-
80Sleep is synchronous, and setTimeout is asynchronous though so there could be some confusion with haphazardly using those implementations. – Dominic Farolino Feb 28 '16 at 05: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 with `setTimeout()`: https://masteringjs.io/tutorials/fundamentals/sleep – vkarpov15 Oct 15 '19 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.

- 33
- 5

- 651
- 5
- 6
-
1
-
1
-
12Also do not do while(1) {}. Another very bad idea. I have a lot of very bad ideas which I will happily share upon request. – clearlight Aug 31 '17 at 17:52
-
1
-
4
-
-
I actually think this is not a bad idea because `sleep` in other languages is blocking the execution – yiwen Aug 11 '19 at 01:43
-
I was thinking the same thing; I wort almost the same fn. ... One force quit later. It's dumb of JS not to know how to take this *while* and put in a hook to continue executing when *time is* type thing instead of hogging the CPU. I would imagine that would be what it should do, seeing as JS only runs on one thread and hogging the CPU is a bad thing. But, no JS does not have a competent sleep function. In lieu, why not a facility like process lock, so that you can tell the program to hold off until other thinks have had time to run? – 9716278 Dec 14 '19 at 21:43