--- title: Cancelling the JavaScript sleep function description: How to cancel a JavaScript sleep function using an AbortSignal. url: https://mattrossman.com/2024/04/10/cancelling-the-javascript-sleep-function/ image: https://mattrossman.com/open-graph/2024/04/10/cancelling-the-javascript-sleep-function.png --- # Cancelling the JavaScript sleep function Apr 10, 2024 A typical JavaScript sleep implementation is this one-liner: ``` const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) ``` In some cases you’ll need cancel this timeout mid-flight. One elegant solution is to accept an [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) similar to other async APIs like [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch#signal). ``` function sleep(ms, signal) { return new Promise((resolve, reject) => { const onAbort = () => { clearTimeout(timeoutId) reject(new Error("Aborted")) } const timeoutId = setTimeout(() => { signal?.removeEventListener("abort", onAbort) resolve() }, ms) signal?.addEventListener("abort", onAbort) }) } ``` TypeScript version ``` function sleep(ms: number, signal?: AbortSignal) { return new Promise((resolve, reject) => { const onAbort = () => { clearTimeout(timeoutId) reject(new Error("Aborted")) } const timeoutId = setTimeout(() => { signal?.removeEventListener("abort", onAbort) resolve() }, ms) signal?.addEventListener("abort", onAbort) }) } ``` Now you can cancel the sleep timeout with [AbortController.abort()](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort). ``` const controller = new AbortController() sleep(1000, controller.signal) .then(() => console.log("done")) .catch(() => console.log("aborted")) // in some other handler... controller.abort() ``` You could certainly return your own `cancel()` method from the sleep function along with the promise, but that would change the familiar function signature. What I like about this abort signal approach is: - It’s unobtrusive—the signal argument is optional, and output is still a plain promise - You can use the same signal to cancel other async processes