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
  });
});

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda