Created
May 28, 2021 18:41
-
-
Save codefrau/91435acb16140e1d2036b15181cf9e0d to your computer and use it in GitHub Desktop.
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, ...args) { | |
const timeout = { cancelled: false }; | |
globalThis.setTimeout(() => timeout.cancelled || func(), ...args); | |
} | |
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