Many languages have a sleep(1000) that stops the program for a second. JavaScript cannot stop: the page has one main thread, and blocking it would freeze scrolling, typing and painting. What it can do is hand back a promise that settles a second later, so an async function can await it and pick up where it left off while everything else keeps running. A real helper also needs a way out: when the user leaves the screen, a pending wait should end at once instead of running code later.
sleep returns a real Promise, and the code after the call runs at once: nothing is blocked.
The promise resolves ms ms after the call, not earlier, and its value is undefined. It leaves no timer behind.
Even sleep(0), sleep(-5) and sleep() wait for a timer: the promise is not resolved before the timer fires.
Awaiting sleeps one after another adds up: await sleep(100); await sleep(200); ends 300 ms after it starts. Sleeps started together resolve in order of their end time, and ones with the same ms in the order they were called.
Aborting the signal while waiting rejects the promise with signal.reason (by default a DOMException named "AbortError", or the reason passed to abort(reason)), and clears the timer.
A signal that is already aborted rejects straight away, without starting a timer.
Once the promise has resolved, aborting the signal changes nothing and causes no error. sleep also removes the abort listener it added, so a long-lived signal does not collect listeners.
One signal can end many sleeps at once.
sleep(ms), sleep(ms, {}) and sleep(ms, { signal: undefined }) all work.
asyncfunctionblink() { console.log("on");awaitsleep(500); console.log("off"); // 500 ms later}blink();console.log("not blocked"); // printed right after "on"
JAVASCRIPT
constcontroller=newAbortController();sleep(5000, { signal: controller.signal }) .then(() => console.log("done")) .catch((error) => console.log(error.name)); // "AbortError"controller.abort(); // ends the wait now
JAVASCRIPT
awaitsleep(0); // still waits for a timer, after the current taskconstalready= AbortSignal.abort();awaitsleep(100, { signal: already }); // rejects at once with an AbortError