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!

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (0)

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

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Debugging Apps in AI using Seer, MCP, and Agent Monitoring

In this live workshop, the Sentry team covers their latest AI updates, including Seer, Sentry's AI Agent, which automates debugging using Tracing, Logs, and Stack Traces.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️