JavaScript sleep/wait


JavaScript, unlike other languages, does not have any method to simulate a sleep() function. There are some approaches that can be used to simulate a sleep function.

The programming languages such as PHP and C has a sleep(sec) function to pause the execution for a fixed amount of time. Java has a thread.sleep(), python has time.sleep(), and GO has time.sleep(2*time.second).

Unlike other languages, JavaScript doesn't have any sleep() function. We can use some approaches for simulating the sleep() function in JavaScript. The features such as promises and async/await function in JavaScript helped us to use the sleep() function in an easier way.

The await is used to wait for a promise and can only be used in an async function. The behavior of JavaScript is asynchronous, so there is a concept of promises to handle such asynchronous behavior. Because of this asynchronous behavior, it continues its work and does not wait for anything during execution. Async/await functions help us to write the code in a synchronous manner.

Method 1: Using an infinite loop to keep checking for the elapsed time

The time that the sleep function starts is first found using the new Date().getTime() method. This returns the number of milliseconds passed since the Epoch time.

An infinite while loop is started. The elapsed time is calculated by subtracting the current time with the starting time. If-statement checks whether the elapsed time is greater than the given time (in milliseconds). On satisfying the condition, a break statement is executed, breaking out of the loop. The sleep function now ends and the lines of code written after the sleep function will now execute.

This type of sleep which uses an infinite loop stall the processing of the rest of the script and may cause warnings from the browser. It is not encouraged to use this type of sleep function for a long duration.

Example

Example