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

Zxce3 @zxce3

About: Nothing

Location:
Riau, Indonesia
Joined:
Feb 10, 2022

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

Publish Date: Apr 25
0 1

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!

Comments 1 total

Add comment