What is the JavaScript version of sleep()? – Definitive Guide

JavaScript does not have any built-in sleep function like other programming languages. The JavaScript version of sleep can be achieved by having some approaches for simulating sleep() operation.

You can use promise asynchronous reusable function new Promise(resolve => setTimeout(resolve, ms)) as the JavaScript version of sleep()

If you are in a hurry
You can use the below asynchronous promise object for handling a delay in executing a task.
Code

    //promise object for handling sleep using the setTimeout()
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    //function that calls promise object to create a delay in executing a task 
    function usingPromise() {
        console.log("1. Process started execution");
        sleep(5000).then(() => console.log("2. Executing after 5 second sleep using promise"));
        console.log("3. Main process completed executed");
    }

Output

    "1. Process started execution"
    "3. Main process completed executed"
    "2. Executing after 5 second sleep using promise"

In the examples, promise creates a delay(sleep) of 5000 milliseconds before executing the linked code asynchronously.

Note:

  • As JavaScript is a single-thread application, it is a bad idea to have a synchronous way of achieving Sleep operation.
  • Synchronous way of achieving JavaScript version of sleep can easily be disruptive to the user experience and should be avoided.

There are a couple of other ways available as a JavaScript version of sleep, and let us see those in detail.

Using setTimeout()

The setTimeout() method acts as a timer which executes the specific piece of code or a function only after the timer expires.
Code

    console.log("1. Process started execution");
    setTimeout(() => {
      console.log("2. Executing after 5 second sleep using set Timeout")
    }, 5000);
    console.log("3. Main process completed executed");

Output

    "1. Process started execution"
    "3. Main process completed executed"
    "2. Executing after 5 second sleep using set Timeout"

This setTimout() will also produce the same effect as promise, but the only difference is code can’t be reused in the setTimeout case.
Let’s see one more example of performing a recursive operation using the setTimeout(),
Code

    //recursive behaviour is achieved with a delay using setTimeout()
    var counter = 0;
    function recursiveOnFailure() {
        counter++;
        console.log("1. Process started execution with counter value : "+counter);
        //below condition can be created based on the requirement to perform a retry
        if (counter == 3) {   
            console.log("2. condition met and process completes execution");
        } else {
            console.log("3. retry after 2 seconds wait");
            setTimeout(() => recursiveOnFailure(), 2000);
        }
    }
    recursiveOnFailure()     //run the above method

Output

    "1. Process started execution with counter value : 1"
    "3. retry after 2 seconds wait"
    "1. Process started execution with counter value : 2"
    "3. retry after 2 seconds wait"
    "1. Process started execution with counter value : 3"
    "2. condition met and process completes execution"

In the above example, until the expected condition is met, retry happens after a sleep time of 2 seconds.
This helps to perform the same operation after a wait time until the expected target(condition) is ready.

Using Promise()

The Promise object represents a asynchronous operation(completion/failure) and its resulting value.
Promise works in an asynchronous manner, so other tasks are not required to wait for a promise to complete its execution, and by this, you can achieve the JavaScript version of sleep.
Code

    //promise method with setTimeout() to create a delay in execution
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    //method to be invoked after a sleep time
    function printMeAfterSleep() {
        console.log("2. Printing after sleep");
    }

    //method to demonstrate promise behavior
    function promiseConsumer() {
        console.log("1. Process started execution");
        promiseSleep(5000).then(() => printMeAfterSleep());
        console.log("3. Main process completed executed");
    }

    promiseConsumer();

Output

    "1. Process started execution"
    "3. Main process completed executed"
    "2. Printing after sleep"

The promise object represents an asynchronous operation; here, the promise (sleep()) method creates a delay of 5 seconds to perform the linked task.
The order of logs confirms the behaviour of the promise to achieve the JavaScript version of sleep,

  • Delay in executing the task based on the timer value(5000 milliseconds).
  • Asynchronous execution by not making other operations wait until the promise completes its execution.

Using async/await

Adding Async keyword makes a function behave to work asynchronously, and Await keyword used to wait for a promise and it can only be inside an Async function.
This also helps to achieve the JavaScript version of sleep, and it is
Code

    //promise function
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    //async function with await keyword to make it wait for the promise to complete its execution
    async function asyncFunction() {
        console.log("2. task to wait for 2 seconds");
        await sleep(2000);
        console.log("3. task to wait for 2 seconds");
        await sleep(2000);
        console.log("4. task completed waiting");
    }

    //method to invoke asynchronous function
    function usingAsyncAwait() {
        console.log("1. Process started execution");
        asyncFunction();
        console.log("5. Main process completed executed");
    }

Output

    "1. Process started execution"
    "2. task to wait for 2 seconds"
    "5. Main process completed executed."
    "3. task to wait for 2 seconds"
    "4. task completed waiting"

In the above example, the async function is invoked and works asynchronously by not making other codes wait for completion.

The 3rd log statement("5. Main process completed executed") confirms this behaviour; before the execution of the async function, the last line of code is executed.

The Await keyword waits for the promise to complete, Here promise function(sleep()) has an objective to sleep(wait) for 2 seconds.

Only after the promise completes its execution does await allow the following line of code to execute inside the async function.

Using Native JavaScript

This is by using a simple JavaScript code to build a custom way of achieving the JavaScript version of sleep,
Code

    function customeSleep(milliseconds) {
        const date = Date.now();
        let currentDate = null;
        do {
            currentDate = Date.now();
        } while (currentDate - date < milliseconds);
    }

    function usingNativeCode() {
        console.log("Started execution");
        customeSleep(2000);
        console.log("Completes with a delay of 2 seconds!");
    }

    usingNativeCode()

Output

    "Started execution"
    "Completes with a delay of 2 seconds!"

Live Demo

Summary

You have learned how to create a JavaScript version of sleep.
You have also learnt about different ways to create JavaScript version of sleep using promise(), setTimeout(), async() and await() and also using native javascript code.

You May Also Like

Leave a Comment