Returns after timeout period.
console.log(`Hello`);await sleep(1000);console.log(`There`); // Prints one second after Copy
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 Copy
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.
requestAnimationFrame
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.
delay()
sleep()
A value can be provided, which is returned on awaking:
const v = await sleep({ seconds: 1, value: `hello`);// v = `hello` Copy
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 1minawait sleep({ minutes: 1, signal: ac.signal });console.log(`Awake`); // This line doesn't get called because an exception is thrown when aborting Copy
const ac = new AbortController();setTimeout(() => { ac.abort(); }, 1000); // Abort after 1s// Sleep for 1minawait sleep({ minutes: 1, signal: ac.signal });console.log(`Awake`); // This line doesn't get called because an exception is thrown when aborting
Milliseconds to sleep, or options
Returns after timeout period.
Example: In an async function
Example: As a promise
If a timeout of 0 is given,
requestAnimationFrame
is used instead ofsetTimeout
.delay and sleep are similar.
delay()
takes a parameter of what code to execute after the timeout, whilesleep()
just resolves after the timeout.A value can be provided, which is returned on awaking:
Provide an AbortSignal to cancel the sleep and throwing an exception so code after the sleep doesn't happen.