SetInterval with exact timeout

Is there a way to make the function the same as setInterval, but the wait time will be the same every time. In setInterval, the timeout varies depending on the specified timeout, a little more, a little less, but very rarely, just like that.

For instance:

var before = new Date().getTime(); setInterval(function() { var after = new Date().getTime(); newTab.window.location=someURL; console.log((after - before)); before = after; }, 50000); 

prints 50000.50002, 50005, 50994, 50997, 49999, 50003, 49998, etc. I want to always print 50,000

+5
source share
1 answer

Javascript is executed in only one thread, therefore, if there is another process executing something at the same time, there is always a chance that the timer function will not be executed on time.

If you really need an accurate time interval, you can block the execution of any other process in advance and hope for the best:

 function setExactInterval(handler, time) { var startTime = Date.now(); setTimeout(function() { while (true) { var currentTime = Date.now(); var diff = currentTime - startTime; if (diff >= time) { setExactInterval(handler, time); return handler(); } } }, time - 50); } 

This will be inaccurate if the process is blocked by the OS, though ...

+3
source

All Articles