In JavaScript, due to its asynchronous nature, a native sleep function isn't available. However, there are plenty of use cases where you might want to pause the execution of your code for a specific amount of time including:

1. Animation: using sleep to control the timing of animations, for example, to delay the movement of an object
2. API Requests: delaying or throttling requests to stick to rate limits
3. Simulating User Interaction: mimicking pauses between user actions like clicks or keystrokes
4. Sequential Code Execution: Ensuring code executes sequentially waiting for one task to complete before moving to next
5. Debugging and Logging: Inserting sleep delays in debugging can provide time to inspect the state of your application
6. Rate Limiting: Using a sleep function can help deal with event triggers
7. Interactive Tutorials: With guided walkthroughs being able to pause execution to read instructions before proceeding
8. Countdowns or Timers: sleep can be employed for display countdowns or triggering an action after a specified period
9. Simulating Real-Time Chat: Having delays between message responses can mimic real-time conversation dynamics
10. Slideshows or Carousels: Can be used to control the timing between transitioning to the next slide or image

There are many more than this, this just touches on some of the popular ones. This custom sleep function can allow you to do everything listed here and anywhere you need your application to sleep or pause. You could sleep for 1 second, 2 seconds, or 10 seconds. You could sleep in a loop so that each iteration pauses for 500ms. You can sleep all day long (your code, not you!).

The way it is set up is that all of our logic will be wrapped in an async function that we call main which will provide us everything we need to be able to sleep whenever needed and wait before executing any other code.

/**
 * Javascript Sleep
 *
 * @params {number} ms - The time in microseconds to sleep. 1000 ms would be 1 second.
 */
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

This code snippet was published on It was last edited on

0

1 Comment

  • Votes
  • Oldest
  • Latest
Commented

Here is an example of how to use this JavasScript Sleep Function:

async function main() {
  console.log('Showing immediately before starting sleep');
  await sleep(5000);
  console.log('Showing after five seconds has passed');
}

main();

The expected output in the browser console:

Showing immediately before starting sleep
Showing after five seconds has passed
add a comment
0