Matthew C.
—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()
?
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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.