有没有办法在浏览器中快进时间来触发页面上设置的setTimeouts?
Is there a way to fast forward time in the browser to trigger setTimeouts set on the page?
我有一个非常烦人的网站,我必须使用它使用 setTimeouts 强制用户在继续之前等待 15 秒,如果能够调用 window.fastForward(15000)
之类的东西来移动它会很棒.
在编写依赖于时间的测试时,有一些人为的方法可以使时间快进,因此我们不必实际等待 30 秒来让测试到达 运行。在任何浏览器中都存在这样的东西吗?
出于测试目的,您可以对默认的 setTimeout 进行猴子修补,下面是一个使 setTimeout 快 10 倍的简单示例。
ps。为了使这段代码更便携,我没有使用 window,而是使用了 globalThis,这允许它在 nodejs 等中工作。对于旧的浏览器,你可以只替换为 window,或者更好的是仍然使用polyfills.
//lets make our timeout's 10 times faster..
const origTimeout = globalThis.setTimeout;
globalThis.setTimeout = function (fn, delay) {
origTimeout.call(this, fn, delay / 10);
}
console.time('done in');
setTimeout(() => {
console.log('Will be done in 10 seconds');
console.timeEnd('done in');
}, 10000);
我有一个非常烦人的网站,我必须使用它使用 setTimeouts 强制用户在继续之前等待 15 秒,如果能够调用 window.fastForward(15000)
之类的东西来移动它会很棒.
在编写依赖于时间的测试时,有一些人为的方法可以使时间快进,因此我们不必实际等待 30 秒来让测试到达 运行。在任何浏览器中都存在这样的东西吗?
出于测试目的,您可以对默认的 setTimeout 进行猴子修补,下面是一个使 setTimeout 快 10 倍的简单示例。
ps。为了使这段代码更便携,我没有使用 window,而是使用了 globalThis,这允许它在 nodejs 等中工作。对于旧的浏览器,你可以只替换为 window,或者更好的是仍然使用polyfills.
//lets make our timeout's 10 times faster..
const origTimeout = globalThis.setTimeout;
globalThis.setTimeout = function (fn, delay) {
origTimeout.call(this, fn, delay / 10);
}
console.time('done in');
setTimeout(() => {
console.log('Will be done in 10 seconds');
console.timeEnd('done in');
}, 10000);