Forked from ahmadalibaloch/customSetTimeoutAndsetInterval.js
Created
October 14, 2022 05:12
-
-
Save neeleshbisht99/c0e8d81878de05ffa02990fcd70f23dd 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