Last active
September 6, 2021 21:06
-
-
Save codefrau/cd7d25ee88f034c71bba9cf6ba51f9b7 to your computer and use it in GitHub Desktop.
Workaround for "Cannot clear a timeout created in a different request context" error in Cloudflare Workers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Replacement for setTimeout/clearTimeout in Cloudflare Workers | |
// Avoids "Cannot clear a timeout created in a different request context" error | |
// | |
// Usage: | |
// import { setTimeout, clearTimeout } from "./cloudflare-timeout.mjs" | |
// | |
// Author: Vanessa "Codefrau" Freudenberg <[email protected]> | |
export function setTimeout(func, ...opts) { | |
const timeout = { cancelled: false }; | |
globalThis.setTimeout((...args) => timeout.cancelled || func(...args), ...opts); | |
return timeout; | |
} | |
export function clearTimeout(timeout) { | |
if (typeof timeout === "object") timeout.cancelled = true; | |
else if ((typeof timeout === "undefined")) return; | |
else throw Error("cloudflare-timeout: clearTimeout() expects object returned from setTimeout()"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment