Skip to content

Instantly share code, notes, and snippets.

@codefrau
Last active September 6, 2021 21:06
Show Gist options
  • Save codefrau/cd7d25ee88f034c71bba9cf6ba51f9b7 to your computer and use it in GitHub Desktop.
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
// 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