You can wrap around the setTimeout
before eval()
the script. When removed the script, you can unregister the tasks.
function mockInternal() {
const setTimeout = window.setTimeout;
const setInterval = window.setInterval;
// window.setImmediate
// window.addEventListener
const setTimeoutHandlers = [];
const setIntervalHandlers = [];
window.setTimeout = function mock_setTimeout(callback, delay) {
const h = setTimeout(callback, delay);
setTimeoutHandlers.push(h);
return h;
}
window.setInterval = function mock_setInterval(callback, delay) {
const h = setInterval(callback, delay);
setIntervalHandlers.push(h);
return h;
}
return function clearMockInternal() {
window.setTimeout = setTimeout;
window.setInterval = setInterval;
setTimeoutHandlers.forEach(h => clearTimeout(h));
setIntervalHandlers.forEach(h => clearInterval(h));
}
}
const clearMockInternal = mockInternal();
eval(`setInterval(() => console.log(new Date()), 1000);`);
setTimeout(() => {
clearMockInternal();
console.log("should not log Date from now");
}, 6000);