Is there a way to fast forward time in the browser to trigger setTimeouts set on the page?

Viewed 1057

I have a very annoying site I have to use that uses setTimeouts to force the user to wait 15 seconds before proceeding, and it would be great to be able to call something like window.fastForward(15000) to move it along.

When writing out tests that depend on timing, there are artificial ways to fast forward time so we don't have to actually wait 30 seconds for a test to run. Does something like this exist in any browser?

1 Answers

For testing purposes you could just monkey patch the default setTimeout, below is a simple example that makes setTimeout 10 times faster.

ps. To make this code more portable, instead of using window I've used globalThis instead, this allows this to then work in nodejs etc. For older browsers you could just replace with window, or better still use 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);

Related