immediato
Version:
An isomorphic setImmediate implementation that doesn't prevent the process from exiting naturally.
42 lines (41 loc) • 1.17 kB
JavaScript
/* HELPERS */
let callbacksId = 0;
let callbacksExecuting = false;
let callbacksMap = new Map();
let { port1, port2 } = new MessageChannel();
/* MAIN */
const setImmediate = (callback, ...args) => {
const callbackId = (callbacksId += 1);
const callbackWithArgs = () => callback(...args);
callbacksMap.set(callbackId, callbackWithArgs);
port1.onmessage = runImmediate;
port2.postMessage(callbackId);
return callbackId;
};
const clearImmediate = (callbackId) => {
callbacksMap.delete(callbackId);
if (callbacksMap.size)
return;
port1.onmessage = null; // Important to reset this, as it will ~hang the process otherwise
};
const runImmediate = (event) => {
const callbackId = event.data;
const callback = callbacksMap.get(callbackId);
if (!callback)
return;
if (callbacksExecuting) {
setTimeout(runImmediate, 0, callbackId);
}
else {
try {
callbacksExecuting = true;
callback();
}
finally {
callbacksExecuting = false;
clearImmediate(callbackId);
}
}
};
/* EXPORT */
export { setImmediate, clearImmediate };