Why Does the sleep() Function in JavaScript Use a Promise?
sleep()
is defined as:
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
Why can't we just use setTimeout()
without a promise involved?
Using a Promise allows us to await
the timer, which we can't do with just setTimeout()
. This allows us to write our code that looks more linear like:
// before await sleep(time); // after await sleep(time); // more
Instead of
// before sleep(time, () => { // after sleep(time, () => { // more }); });
I have created a set of resources for learning asynchronous JavaScript. These guides—Callbacks, Promises, and Async/Await —cover everything I’ve learned from years of real-world JavaScript experience.
If you found this article helpful, you’ll get so much out of these guides. Each one is optimized for those “lightbulb moments,” building a strong mental model for how asynchronous JavaScript works and how you can use it to create fast, dynamic applications.