Skip to content

Instantly share code, notes, and snippets.

@codefrau
Created May 28, 2021 18:41
Show Gist options
  • Save codefrau/91435acb16140e1d2036b15181cf9e0d to your computer and use it in GitHub Desktop.
Save codefrau/91435acb16140e1d2036b15181cf9e0d to your computer and use it in GitHub Desktop.
// 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