Skip to content

Instantly share code, notes, and snippets.

@kriskowal
Last active August 29, 2021 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kriskowal/8563cb7741ad0206eec0f01dbc28fefe to your computer and use it in GitHub Desktop.
Save kriskowal/8563cb7741ad0206eec0f01dbc28fefe to your computer and use it in GitHub Desktop.
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);
@michaelfig
Copy link

setTimeout needs to return token;.

Also, it might be good for clearTimeout to assert that handle is truthy.

@erights
Copy link

erights commented Aug 26, 2021

If the real setTimeout is given a string as callback, setTimeout will eval it!

@kriskowal
Copy link
Author

Thanks @michaelfig, that was accidentally omitted. Thanks @erights, that was deliberately omitted! 😉

@kriskowal
Copy link
Author

@erights, Oh, I see what you mean!

@kriskowal
Copy link
Author

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.

@michaelfig
Copy link

Might be safer to throw if the callback is not a function.

@erights
Copy link

erights commented Aug 27, 2021

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.

@erights
Copy link

erights commented Aug 29, 2021

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment