DEV Community

Cover image for Sleep function in javaScript
Rahul kumar
Rahul kumar

Posted on

Sleep function in javaScript

JavaScript provides setTimeout() and setInterval() methods to delay execution of script. But, it doesn't provide any way to sleep execution at a single line. Let's build our custom sleep method.

TOC

  1. Prerequisites
  2. idea
  3. sleep API
  4. uses
  5. live interactive demo

Prerequisites

I am assuming that you know the above prerequisites.

Idea is to use a promise to wait for a number of milliseconds. We know, we can delay the execution of certain script using await. Using await we can run the next script after the promise is resolved or rejected.

Let's build our sleep API

function sleep(ms){
  return new Promise((resolve)=>{
    setTimeout(()=>resolve(),ms);
  })
}
Enter fullscreen mode Exit fullscreen mode

The above sleep API will wait for some milliseconds, then it resolves the promise.

Uses

make sure to call this API inside the async function

async function test(){
    // wait for 3 seconds
    console.log("Waiting...");
    await sleep(3000); 
    console.log("The wait is over");
}
Enter fullscreen mode Exit fullscreen mode

Live demo

See the Pen oNzpMZN by Rahul kumar
(@ats1999) on CodePen.

Top comments (8)

Collapse
 
qm3ster profile image
Mihail Malo

I usually write it as

const sleep = ms => new Promise(res => setTimeout(res, ms))
Enter fullscreen mode Exit fullscreen mode

since there's no reason to introduce an additional closure.
You can also do that with value (that promise will resolve to) since setTimeout supports passing arguments.

const sleep = (ms, v) => new Promise(res => setTimeout(res, ms, v))
sleep(500, "hello").then(console.log)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ats1999 profile image
Rahul kumar

.then(console.log)
I usually avoid to chaining in this case. Await would be great fit here.

Collapse
 
ats1999 profile image
Rahul kumar

Although great example
const sleep = ms => new Promise(res => setTimeout(res, ms))

Collapse
 
ironcladdev profile image
Conner Ow

Why would you go through all that work of creating a javascript promise when you can just use the setTimeout function and the clearInterval function?

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

To avoid "callback hell". Promises with async/await allow you to write asynchronous code linearly, rather than nesting callbacks, which quickly becomes messy.

If you might need to clear the timeout before it executes, the callback version is probably better though (you could build a clearable promise version, but it would be less easy to work with). Depends on your use case.

Collapse
 
ats1999 profile image
Rahul kumar

agree

Collapse
 
ats1999 profile image
Rahul kumar

Supposed in case, where you want to use sleep many times. If code goes long, say 1000 lines of code. In this case, it becomes hard to manage the code.
Here we can just use,

await sleep(ms);
// do after sleep();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ats1999 profile image
Rahul kumar

code and sleep 🥱