DEV Community

Zxce3
Zxce3

Posted on

Implementing Delay/Sleep in JavaScript with Promises and Async/Await

Sometimes, you need to pause execution in JavaScript, like waiting for an API response or adding a delay between actions. Here’s how you can implement a delay (or sleep) function using modern JavaScript.

Using Promises

The setTimeout function is great for delays. Combine it with promises to create a reusable delay function:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
Enter fullscreen mode Exit fullscreen mode

This function resolves the promise after the specified time in milliseconds (ms).

Using Async/Await

With async/await, you can make the delay work like a synchronous pause inside asynchronous functions:

async function example() {
  console.log('Start');
  await delay(2000); // Pause for 2 seconds
  console.log('End');
}
example();
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • delay(ms) returns a promise that resolves after ms milliseconds.
  • await pauses execution in an async function until the promise resolves.

Why Use This Method?

It’s clean, modern, and avoids callback hell. Perfect for developers looking to write readable asynchronous code.

Got questions? Drop them below!

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →