Create a gist now

Instantly share code, notes, and snippets.

Accurate Javascript setInterval replacement
function interval(duration, fn){
this.baseline = undefined = function(){
if(this.baseline === undefined){
this.baseline = new Date().getTime()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
nextTick = 0
i.timer = setTimeout(function(){
}, nextTick)
this.stop = function(){

This code snippet can be used when a very accurate setInterval is needed. It will always be accurate ( 1+-ms in variance, but the mean will be the exact duration). Of course the function provided must run faster than the duration parameter. If for some reason the function takes more time than the duration in some occasions, the timer will still converge to the exact intervals very fast.

Example of use:

var timer = new interval(50, function(){
      console.log(new Date().getTime())

Did you snag this from another programming language?


I did not, but this was written when I was quite new in javascript. I have a better version of this code in our framework:

But of course it depends on other things, it is not lightweight as the one in the gist. In any case I am planing a new interval/timer that is a bit more powerful, I want to be able to keep just one timer for all the intervals instances.


on line 20 shouldn't be


instead of




You are tight ezabba




@manast - I've implemented a new version of this at

Rather than calculate the difference between an updated baseline, this instead takes a start time and current time, and calculates a pretty accurate tick value to compensate for drift - I've had this running for hours and keep accurate to within 1-5ms.

A bonus of this version if you use the default 1000ms (1s) tick value, it also gives you an accurate H/M/S timing, as shown in the timer example


This has a problem, when the window lose the focus, the timers speed up after focus again.


Good code, integrated it and works perfect!


I would add

timer &&;

Why? Consider the code below:

        var si = new interval(50, function () {
                if ("undefined" !== typeof hiddenPreloadImage && hiddenPreloadImage && 0 !== si) {
                    si = 0;
                    setStyleOpacity(superbox, 1),
                    setImmediate(function () {
                        window.progressBar && (progressBar.finish(), progressBar.hide());
        si &&;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment