Last active
December 7, 2022 07:34
-
-
Save ahmadalibaloch/6c7d70244c83b90aa77bb83fa28cd0df to your computer and use it in GitHub Desktop.
custom setTimeout and setInterval for sandbox environments in browsers (vm-browserify or node-vm)
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 setTimeouts = []; | |
export function customSetTimeout(cb, interval) { | |
const now = window.performance.now(); | |
const index = setTimeouts.length; | |
setTimeouts[index] = () => { | |
cb(); | |
}; | |
setTimeouts[index].active = true; | |
const handleMessage = (evt) => { | |
if (evt.data === index) { | |
if (window.performance.now() - now >= interval) { | |
window.removeEventListener('message', handleMessage); | |
if (setTimeouts[index].active) { | |
setTimeouts[index](); | |
} | |
} else { | |
window.postMessage(index, '*'); | |
} | |
} | |
}; | |
window.addEventListener('message', handleMessage); | |
window.postMessage(index, '*'); | |
return index; | |
} | |
export function customClearTimeout(setTimeoutId) { | |
if (setTimeouts[setTimeoutId]) { | |
setTimeouts[setTimeoutId].active = false; | |
} | |
} | |
const setIntervals = []; | |
export function customSetInterval(cb, interval) { | |
const intervalId = setIntervals.length; | |
setIntervals[intervalId] = function () { | |
if (setIntervals[intervalId].active) { | |
cb(); | |
customSetTimeout(setIntervals[intervalId], interval); | |
} | |
}; | |
setIntervals[intervalId].active = true; | |
customSetTimeout(setIntervals[intervalId], interval); | |
return intervalId; | |
} | |
export function customClearInterval(intervalId) { | |
if (setIntervals[intervalId]) { | |
setIntervals[intervalId].active = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But in node's vm the window is not defined. So I guest here is some polyfill needed or some other event emmiter which would then be another event loop, not?