Function sleep

Returns after timeout period.

console.log(`Hello`);
await sleep(1000);
console.log(`There`); // Prints one second after
console.log(`Hello`);
sleep({ millis: 1000 })
.then(() => console.log(`There`)); // Prints one second after

If a timeout of 0 is given, requestAnimationFrame is used instead of setTimeout.

delay and sleep are similar. delay() takes a parameter of what code to execute after the timeout, while sleep() just resolves after the timeout.

A value can be provided, which is returned on awaking:

const v = await sleep({ seconds: 1, value: `hello`);
// v = `hello`

Provide an AbortSignal to cancel the sleep and throwing an exception so code after the sleep doesn't happen.

const ac = new AbortController();
setTimeout(() => { ac.abort(); }, 1000); // Abort after 1s

// Sleep for 1min
await sleep({ minutes: 1, signal: ac.signal });
console.log(`Awake`); // This line doesn't get called because an exception is thrown when aborting
  • Type Parameters

    • V

    Parameters

    • optsOrMillis: SleepOpts<V>

      Milliseconds to sleep, or options

    Returns Promise<undefined | V>