What is the JavaScript Version of `sleep()`?

Matthew C.

The Problem

You may be familiar with another language, such as Python, that has a sleep() function. The Python time module has a built-in sleep() method that you can use to delay the execution of a program. The time delay, in seconds, is passed in as an argument:

import time time.sleep(delayInSeconds)

What is the JavaScript version of sleep()?

The Solution

To replicate the Python sleep() method, you can make a JavaScript sleep function using a Promise() constructor and setTimeout:

function sleep(ms = 0) { return new Promise(resolve => setTimeout(resolve, ms)); }

You could also write it on one line using an arrow function:

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

You can then use the sleep function to delay the execution of a program. For example, the delayedGreeting function as shown in the code below is paused for five seconds:

async function delayedGreeting() { await sleep(5000); console.log("hello"); } delayedGreeting();

The sleep function takes in a time in milliseconds as an argument. It’s set to 0 as a default here. It returns a Promise, which is an object that represents the eventual completion or failure of an asynchronous (async) operation.

A promise has three possible states:

  • Pending: The object’s initial state, neither fulfilled nor rejected.

  • Fulfilled: The operation was completed successfully.

  • Rejected: The operation failed.

You can attach callbacks to an async function that returns a promise to handle the two possible outcomes:

asyncFunctionThatReturnsPromise(options).then(successCallback, failureCallback);

If the promise is fulfilled, successCallback will be called. If it is rejected, failureCallback will be called.

Promises allow async methods to return values like synchronous methods. The async method returns a promise to give the value later. You can use the await operator to wait for the promise to be resolved.

const value = await asyncFunctionThatReturnsPromise();

The Promise() constructor is used to wrap around callback functions that don’t support promises, such as setTimeout. It allows us to resolve or reject a promise manually, which means we can use setTimeout to delay the execution of a function. The sleep function’s returned promise is resolved using the resolve method after the setTimeout timer expires. This occurs after the successful completion of the setTimeout function. The value of the resolved promise is undefined; the promise is used to pause execution so it does not need a returned value. The promise does not include a reject as setTimeout does not really fail.

When using the sleep function to pause execution, the await operator is used to wait for the returned promise in the sleep function to be resolved. It can only be used in an async function or at the top level of a module.

Get Started With Sentry

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a JavaScript project and note your DSN

  3. Grab the Sentry JavaScript SDK

<script src="https://browser.sentry-cdn.com/7.111.0/bundle.min.js"></script>
  1. Configure your DSN
Sentry.init({ dsn: 'https://<key>@sentry.io/<project>' });

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.