JavaScript - sleep function

6 points
Created by:

In this short article, we're going to have a look at how in JavaScript create sleep(ms) function.

Quick solution:

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// await sleep(1000);  // <------ use it inside async function

Node: async/await operators were introduced in ES8 (ES2017)  - use Babel or TypeScript to provide this functionality in older browsers.



There is no available sleep function in JavaScript, but it is possible to emulate sleeping with acync functions. The main idea is to postpone resolve function call with setTimeout wrapped in Promise object. Later that create logic can be placed inside own sleep function and called with await keyword inside async method only - it is the main disadvantage/advantage of the approach. Advantage because our logic will not freeze the web browser as infinity loop does.

More complicated runnable example code below:

// ONLINE-RUNNER:browser;

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// Usage example:

const action = async () => {
    for (let i = 0; i < 5; ++i) {
        await sleep(1000); // sleeps 1s each iteration

Alternative titles

  1. JavaScript - delay function
  2. JavaScript - pause function
  3. JavaScript - wait function executing
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂