Is there a sleep function in JavaScript?
- 8The modern practice is to simply use
await sleep(<duration>).Dan Dascalescu– Dan Dascalescu2016-10-07 10:30:05 +00:00CommentedOct 7, 2016 at 10:30 - 1please have a look at this answerstackoverflow.com/a/39914235/7219400Sahin– Sahin2022-01-31 19:10:09 +00:00CommentedJan 31, 2022 at 19:10
- 2The 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– Sahin2023-08-23 15:58:33 +00:00CommentedAug 23, 2023 at 15:58
4 Answers4
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'.
5 Comments
await sleep(3000).await sleep seems the newsettimeout .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
You can use thesetTimeout orsetInterval functions.
2 Comments
await on a promise withsetTimeout():masteringjs.io/tutorials/fundamentals/sleepfunction 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
Explore related questions
See similar questions with these tags.










