← Download MyJS

MyJS block

sleep 1.0.0

Waits for a number of milliseconds. Use it with `await` to pause an async function without blocking anything else.

Download with this
Exports
sleep
Works in
Browser and Node.js
The code of version 1.0.0
/**
 * Waits for a number of milliseconds. Use it with `await` to pause an async
 * function without blocking anything else.
 * @param {number} ms
 *    How long to wait, in milliseconds.
 * @param {AbortSignal} [signal]
 *    Stops the wait early. The promise then rejects with the signal's reason
 *    (an `AbortError` unless `abort()` was given one), the same way `fetch`
 *    does.
 * @returns {Promise.<undefined>}
 *    Resolves after `ms` milliseconds.
 *
 * @example <caption>Pausing between steps</caption>
 * console.log('Starting…');
 * await sleep(1000);
 * console.log('One second later');
 *
 * @example <caption>Stopping the wait early</caption>
 * const controller = new AbortController();
 * setTimeout(() => controller.abort(), 100);
 * try {
 *   await sleep(5000, controller.signal);
 * }
 * catch (e) {
 *   console.log(e.name);  // → AbortError
 * }
 */
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }
    const onAbort = () => {
      clearTimeout(timer);
      reject(signal.reason);
    };
    const timer = setTimeout(() => {
      signal?.removeEventListener('abort', onAbort);
      resolve();
    }, ms);
    signal?.addEventListener('abort', onAbort, { once: true });
  });
}

Versions

  1. 1.0.0 Oct 23, 2026

    Initial

JSDoc