Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

delay

Returns a promise that resolves after the specified delay in milliseconds.

TypeScript
Copied!
1/**
2 * Returns a promise that resolves after the specified delay in milliseconds.
3 *
4 * @param ms - The number of milliseconds to wait before resolving.
5 * @returns A promise that resolves after the delay.
6 *
7 * @example
8 * await delay(1000); // waits for 1 second
9 */
10export function delay(ms: number): Promise<void> {
11  return new Promise(resolve => setTimeout(resolve, ms));
12}
  • Simple Time-Based Control

    Provides an easy way to pause async workflows without blocking the event loop.

  • Promise-Based Design

    Naturally fits into async/await code, making delays clean and readable.

  • Cross-Environment Compatibility

    Uses setTimeout, which is universally available in browsers and Node.js.

  • Minimal and Reusable

    Lightweight implementation with no external dependencies, perfect for repeated use in timers, testing, or scheduling logic.

Tests | Examples

TypeScript
Copied!
1jest.useFakeTimers();
2
3test('delay - resolves after specified time', async () => {
4  const fn = jest.fn();
5
6  const promise = delay(2000).then(fn);
7
8  // Advance only part of the delay
9  jest.advanceTimersByTime(1999);
10  await Promise.resolve(); // flush microtasks
11  expect(fn).not.toHaveBeenCalled();
12
13  // Complete the delay
14  jest.advanceTimersByTime(1);
15  await promise;
16  expect(fn).toHaveBeenCalledTimes(1);
17});
18
19test('delay - resolves immediately with 0ms', async () => {
20  const fn = jest.fn();
21
22  const promise = delay(0).then(fn);
23
24  jest.advanceTimersByTime(0);
25  await promise;
26  expect(fn).toHaveBeenCalled();
27});

Common Use Cases

  • Throttling or Rate Limiting

    Introduce spacing between API requests or repeated actions to avoid overwhelming systems.

  • Retry or Backoff Logic

    Wait before retrying failed operations in combination with utilities like retry().

  • Test Timing Control

    Simulate delays or wait for side effects to settle during automated testing.

  • User Feedback Timing

    Delay transitions, loaders, or animations to improve UX pacing.

  • Polling and Scheduled Tasks

    Pause between iterations of a loop when implementing custom polling logic or periodic checks.

Codebase: Utilities -> Functions -> delay | Yevhen Klymentiev