Skip to content
VersionSize

sleep

The sleep utility returns a Promise that resolves after a specified amount of time. It is a modern replacement for setTimeout when working with async/await, allowing you to pause execution in a clean, readable way.

Implementation

View Source Code
ts
import { assert } from './assert';

/**
 * Creates a Promise that resolves after a specified amount of time.
 *
 * @example
 * ```ts
 * sleep(1000).then(() => console.log('Hello, world!')); // logs 'Hello, world!' after 1 second
 * ```
 *
 * @param timeout - The number of milliseconds to wait before resolving the Promise.
 *
 * @returns A Promise that resolves after the specified time.
 *
 * @throws {TypeError} If timeout is not a non-negative number.
 */
export async function sleep(timeout: number): Promise<void> {
  assert(
    typeof timeout === 'number' && timeout >= 0 && Number.isFinite(timeout),
    'Timeout must be a non-negative finite number',
    { args: { timeout }, type: TypeError },
  );
  return new Promise((resolve) => setTimeout(resolve, timeout));
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Promise-based: Native integration with async/await.
  • Lightweight: Minimal footprint, perfect for simple delays.

API

ts
function sleep(ms: number): Promise<void>;

Parameters

  • ms: The number of milliseconds to pause execution.

Returns

  • A Promise that resolves after the specified duration.

Examples

Basic Delay

ts
import { sleep } from '@vielzeug/toolkit';

async function process() {
  console.log('Step 1');
  await sleep(1000); // Wait 1 second
  console.log('Step 2');
}

Polling Example

ts
import { sleep } from '@vielzeug/toolkit';

async function checkStatus() {
  let ready = false;
  while (!ready) {
    ready = await pollApi();
    if (!ready) {
      await sleep(2000); // Check every 2 seconds
    }
  }
}

Implementation Notes

  • Performance-optimized using the native setTimeout.
  • If 0 or a negative number is provided, the Promise resolves in the next event loop tick.
  • Throws TypeError if the argument is not a number.

See Also

  • delay: Pause execution and then run a callback.
  • retry: Automatically retry failed operations with a delay.
  • predict: Wait until a specific condition is met.