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 milliseconds 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

Contributing Authors

0

2 Comments

  • Votes
  • Oldest
  • Latest
Commented
Updated

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
Commented

This is the proper approach to think about it and is essentially the classic JavaScript Sleep pattern. The crucial point that many people overlook is that this is returning control to the event loop rather than "sleeping" the thread. nothing blocks, timers still fire, UI stays responsive.

one thing worth bringing out though: sleep only makes sense when combined with async/await. putting this into non-async code and expecting synchronous behavior is where individuals get confused. You should mentally interpret "pause this async function, not the runtime" as soon as you see await sleep(...).

Additionally, a minor but crucial point: setTimeout operates in milliseconds, yet your document comment states microseconds. that mismatch trips folks up when they start tuning delays.

for real-world usage, this shines in retry/backoff logic and rate limiting loops. something like:

for (let i = 0; i < retries; i++) {
  • 0
    Thanks I changed the docblock from microseconds to milliseconds. — Brian Wozeniak
add a comment
0

User

Community

Market

Help Center

Legal

Company

Social Media