delay
Returns a promise that resolves after a given number of milliseconds. Creates an artificial delay using Promise and setTimeout. Useful for implementing timeouts, rate limiting, animation delays, or simulating async operations in testing.
Installation
npx fragmen add promise/delaySource Code
/**
* Returns a promise that resolves after a given number of milliseconds.
*
* Creates an artificial delay using Promise and setTimeout. Useful for implementing
* timeouts, rate limiting, animation delays, or simulating async operations in testing.
*
* @tags async
* @param {number} ms The number of milliseconds to delay before resolving.
* @returns {Promise<void>} A promise that resolves to void after the specified delay.
*
* @example
* ```typescript
* // Simple delay
* await delay(1000); // Wait 1 second
* console.log('This runs after 1 second');
*
* // In async function
* async function fetchWithDelay() {
* console.log('Starting...');
* await delay(500);
* console.log('Fetching data...');
* return fetch('/api/data');
* }
*
* // Rate limiting
* for (const item of items) {
* await processItem(item);
* await delay(100); // 100ms between each item
* }
* ```
*/
export function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
Examples
// Simple delay
await delay(1000); // Wait 1 second
console.log('This runs after 1 second');
// In async function
async function fetchWithDelay() {
console.log('Starting...');
await delay(500);
console.log('Fetching data...');
return fetch('/api/data');
}
// Rate limiting
for (const item of items) {
await processItem(item);
await delay(100); // 100ms between each item
}
Related Utilities
all-settled-typed
promiseType-safe Promise.allSettled with separated results
retry
promiseRetries a promise-returning function a specified number of times with exponential backoff. Attempts to execute the function, and if it fails, retries up to the specified number of times. Each retry waits longer than the previous one (exponential backoff). Useful for handling flaky network requests, rate-limited APIs, or temporary failures.
timeout
promiseWraps a promise with a timeout, rejecting if it doesn't resolve within the specified time. Creates a race between the provided promise and a timeout. If the promise doesn't resolve or reject before the timeout, it will be rejected with a timeout error. Useful for preventing indefinite hangs, enforcing SLAs, or handling slow operations gracefully.
Quick Actions
Tags
Parameters
msnumberThe number of milliseconds to delay before resolving.
Returns
Promise<void>A promise that resolves to void after the specified delay.