Last active
August 29, 2021 04:51
-
-
Save kriskowal/8563cb7741ad0206eec0f01dbc28fefe 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
const {setTimeout, clearTimeout} = globalThis; | |
const handles = new WeakMap(); | |
globalThis.setTimeout = (callback, ms) => { | |
if (typeof callback !== 'function') { | |
throw new Error(`This implementation of setTimeout has disabled evaluation behavior for ${typeof callback} callbacks`); | |
} | |
const token = harden({}); | |
handles.set(token, setTimeout(callback, ms)); | |
return token; | |
}; | |
harden(globalThis.setTimeout); | |
globalThis.clearTimeout = token => { | |
const handle = handles.get(token); | |
if (handle !== undefined) { | |
handles.delete(handle); | |
clearTimeout(handle); | |
} | |
}; | |
harden(globalThis.clearTimeout); |
If the real setTimeout is given a string as callback, setTimeout will eval it!
Thanks @michaelfig, that was accidentally omitted. Thanks @erights, that was deliberately omitted! 😉
@erights, Oh, I see what you mean!
While I had deliberately omitted an emulation of the stringy callback behavior, I had not deliberately forbidden passing a string through. I’ve posted an update.
Might be safer to throw if the callback is not a function.
Yes, please throw. When we deviate from standard semantics, whether de facto or de jure, we should not just continue silently as we would have if everything succeeded.
LGTM
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
setTimeout
needs toreturn token;
.Also, it might be good for
clearTimeout
to assert thathandle
is truthy.