Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval with exact timeout

Tags:

javascript

Is there some way to make a function just like the setInterval but the timeout to be exactly the same each time. In setInterval the timeout varies about the given timeout, a little bit more, a little bit less, but very rare exactly the same.

For example:

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 and so on. I want to be printed always 50000

like image 438
Hristo93 Avatar asked Oct 19 '22 06:10

Hristo93


1 Answers

Javascript is executed in one flow only, so if there is another process doing something at the same time, there's always a chance you timer function will not be executed in time.

If you really need the exact 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);
}

It still will not be exact in case the process is blocked by OS though...

like image 174
Maxim Gritsenko Avatar answered Oct 22 '22 00:10

Maxim Gritsenko