Skip to main content

How to Resolve a Promise After a Delay in JavaScript

A common requirement in asynchronous programming is to introduce a pause or a delay. You might need to wait for an animation to finish, poll an API endpoint, or simply create a "sleep" function to pause execution. The standard and most effective way to achieve this is by wrapping setTimeout in a Promise.

This guide will teach you how to create a simple and reusable delay function that returns a Promise, which resolves after a specified amount of time.

The Core Method: Wrapping setTimeout in a Promise

The setTimeout function is a classic callback-based API. To use it in a modern, async/await-friendly way, we need to "promisify" it.

Problem: you need to pause the execution of an async function for a specific duration.

async function myAsyncFunction() {
console.log('Starting...');
// How do we wait here for 2 seconds?
console.log('Finished after 2 seconds.');
}

Solution: this small utility function is all you need. It creates a Promise that resolves after the given number of milliseconds.

/**
* Returns a Promise that resolves after a specified number of milliseconds.
* @param {number} ms The number of milliseconds to wait.
* @returns {Promise<void>}
*/
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

// Example Usage:
async function myAsyncFunction() {
console.log('Starting...');

await delay(2000); // Pauses the function for 2000ms (2 seconds)

console.log('Finished after 2 seconds.');
}

myAsyncFunction();

Output:

Starting...
Finished after 2 seconds.

How the delay Function Works

Let's break down the one-liner new Promise(resolve => setTimeout(resolve, ms)).

  1. new Promise(resolve => ...): We create a new Promise. The function we pass to the constructor receives a resolve function as its argument. When we call resolve(), the Promise will be successfully fulfilled.
  2. setTimeout(resolve, ms): This is the core of the trick. We schedule the resolve function itself to be called after ms milliseconds.
  3. When the timer finishes, setTimeout invokes resolve(), which in turn fulfills the Promise.

How to Use the delay Function with .then()

If you are not in an async function, you can use the standard .then() syntax to execute code after the delay.

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

console.log('Starting timer...');

delay(2000).then(() => {
// This code runs after the 2-second delay.
console.log('Timer finished.');
});

Output:

Starting timer...
Timer finished.

The async/await syntax is the modern and most readable way to work with promises, making asynchronous code look synchronous. This is the primary use case for a delay function.

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

async function runWorkflow() {
console.log('Step 1: Starting operation...');
await delay(1500); // Wait for 1.5 seconds

console.log('Step 2: Performing next operation...');
await delay(1000); // Wait for 1 second

console.log('Step 3: Workflow complete.');
}

runWorkflow();

Output:

Step 1: Starting operation...
Step 2: Performing next operation...
Step 3: Workflow complete.

How to Pass a Value Through the Delay

Sometimes you might want the Promise to resolve with a specific value after the delay. This can be easily added to our utility function.

/**
* Returns a Promise that resolves with a given value after a specified delay.
* @param {number} ms The number of milliseconds to wait.
* @param {*} value The value to resolve with.
* @returns {Promise<T>}
*/
function delayWithValue(ms, value) {
return new Promise(resolve => {
setTimeout(() => {
resolve(value);
}, ms);
});
}

// Example Usage:
async function fetchDataAfterDelay() {
console.log('Waiting for data...');
const data = await delayWithValue(2000, { id: 1, name: 'Alice' });

console.log('Data received:', data);
}

fetchDataAfterDelay();
// Output after 2 seconds:
// Data received: { id: 1, name: 'Alice' }

Output:

Waiting for data...
Data received: {id: 1, name: 'Alice'}

Conclusion

Creating a delay or sleep function in JavaScript is a simple but powerful technique for controlling asynchronous workflows.

  • The best practice is to create a reusable function that wraps setTimeout in a Promise.
  • This "promisified" delay function can then be used seamlessly with modern async/await syntax, making your code highly readable and easy to maintain.
  • The one-liner new Promise(resolve => setTimeout(resolve, ms)) is all you need for a simple, effective delay.