I found a function to create a self correcting interval in JS since setInterval
cannot be trusted to be accurate. When logging out the nextTick
, when the interval is 1 second, 1 100th of a second, or 1 10th of a second, the nextTick
, which is the drift fixer upper (to be technical) prints as expected.
Instead of the next tick being 1000 miliseconds, it's usually 999, sometimes 998. Following the aforementioned intervals, you see values such as 99, 98 for 100ths, and usually 9 for 10ths of a second.
Now, when it comes to milliseconds - that is creating an interval that is supposed to be called every millisecond, the nextTick
is printing out NaN or negative numbers. I supposed this is just because the interval is so small. I am wondering if its even possible to get accuracy down to 1 ms
class Interval {
constructor(interval, onTick){
this.interval = interval;
this.onTick = onTick || function(){};
this.timer = false;
this.ticks = 0;
this.startTime = 0;
this.currentTime = 0;
this.elapsedTime = 0;
return this;
}
run(){
this.currentTime = Date.now();
if(!this.startTime){
this.startTime = this.currentTime;
}
this.onTick();
let nextTick = this.interval - (this.currentTime - (this.startTime + (this.ticks * this.interval)));
//console.log(nextTick);
this.ticks++;
let self = this;
this.timer = setTimeout(function(){
self.run();
}, nextTick);
return this;
}
start(){
this.run();
return this;
}
stop(){
clearTimeout(this.timer);
return this;
}
}
In the fiddle you could uncomment one by one the interval constructors to see what I mean.