How to Make JavaScript Functions Sleep

It is quite common to need a JavaScript function pause for a fixed period of time before resuming. Most popular server-side programming languages have native sleep functions, though, with JavaScript this is not the case. Like with most programing problems we can get around this another way.

 

In June 2018 JavaScript introduced Promise which we can use to wait for the response from setTimeout. The default behaviour of Promise is asynchronous meaning the rest of the program will continue to run while the Promise method executes.

 

To make Promise synchronous we can use await.

 

async function doSomething() {

    await new Promise(resolve => setTimeout(resolve, 4000));
    console.log('Four seconds later');

}

doSomething();

 

note - you have to put Promise inside an async function or you will get an Uncaught SyntaxError: await is only valid in async function.

 

Let's elaborate on the above example by implementing a sleep function that we can easily call anywhere in our code.

 

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

async function doSomething() {

   await sleep(2000);
   console.log('Four seconds later do something...');

}

doSomething();

 

Creating a sleep function and then awaiting its return means we can call it easily anywhere in the code by using await sleep(seconds). Let's make a for loop that loops on a two-second cycle. The rest of the code is just an arbitrary example.

 

async function strToArray(word, seconds) {

  var chars = [];

  for (let char of word) {
     chars.push(char);
     await sleep(seconds);
  }

  console.log(chars);
}

var word = 'hello';
var seconds = 2000;
strToArray(word, seconds);

 

A more simple usage of the sleep function would be to add a callback to sleep.

 

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

sleep(2000).then(() => {
    //do something
});

 

 

Conclusion

You now know the most up-to-date way to implement sleep in your JavaScript program.