Sleep function in Javascript

February 16, 2020

There are times while writing javascript, when we might want to halt the execution of Javascript for a small period say 2 seconds. May be while writing test cases, or avoiding race condition, etc. Javascript provides (natively) no way to do this, but we can write our own sleep function.

To do this we will use Promise/await, setTimeout (let’s just face it no one wants to use callbacks anymore 🀐).

The sleep function
const sleep = (sec = 2) => {
  const ms = sec * 1000;
  return new Promise(resolve => {
    setTimeout(resolve, ms)
const delay = 5; // time in seconds
const taskToBeDoneAfterWait = () => console.log('done');

// with Promise
// this will wait for minimum 3 seconds before executing taskToBeDoneAfterWait

// with await 😎
await sleep(delay);
// execution stopped for 3 seconds
// executed after 3 seconds

Sleep function in action

Sleep function in action

That’s it, this is all we need to create our own sleep/wait function.
Hope this helps 😊

Trishul Goel

Trishul Goel is a professional frontend developer; writes React code for living and volunteers for Mozilla to justify his existence.