DEV Community

Zxce3
Zxce3

Posted on

1

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!

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

Top comments (0)

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

JavaScript-ready auth and billing that just works

JavaScript-ready auth and billing that just works

Stop building auth from scratch. Kinde handles authentication, user management, and billing so you can focus on what matters - shipping great products your users will love.

Get a free account

👋 Kindness is contagious

Take a moment to explore this thoughtful article, beloved by the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A heartfelt "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay