SO Answer / chrome setInterval() for blurred tabs not working correctly, even for periods of 1 second or larger

See also: http://stackoverflow.com/questions/17466516/chrome-setinterval-for-blurred-tabs-not-working-correctly-even-for-periods-of

by KooiInc MeHere

HTML

<script src="http://www.nicon.nl/genericsvc/fiddle/fiddlemeta.js"></script>
<button id="stop">stop</button>
<button id="start">start</button>
<input type="text" size="2" value="600"> seconds

JavaScript

/**
 * ---------------------------------------------------------------------------
 * this jsFiddle uses some external helper scripting (the Helper
 * pseudo namespace). See External Resources
 * ---------------------------------------------------------------------------
 **/

// initialize time
var endTime = new Date
   ,startTime = new Date
   ,secondsAhead = +(document.querySelector('input').value) || 600
   ,stopped = false;

// set the end time of the timer (in seconds from now)
endTime.setSeconds(endTime.getSeconds()+secondsAhead);
endTime.setMilliseconds(0);

// timer method, recursive. Whilst the current time 
// is smaller than the projected end time [endTime] 
// a timeout is initialized, running this method 
// after a second (1000ms). The  facto it is thus 
// running for the duration of endTime - startTime.
function countDown(){
    var diff = Math.ceil((endTime-new Date)/1000);
    Helper.log();
    Helper.log(String.Format(
                '<b>{0}:{1}:{2}</b>'
                ,zeroPad(Math.floor(diff/3600))
                ,zeroPad(Math.floor((diff/60)%60))
                ,zeroPad(Math.floor((diff%60)))
              )
    );
   
    if (!stopped && diff >= 1) {
        setTimeout(countDown,1000);
    } else {
        Helper.log(
            String.Format(
                '<b>Done</b>:{2}<br>started: {0}<br>ended {1}'
                ,startTime
                ,new Date
                ,stopped ? '<br><i>stop button clicked</i>' : '')
        )
    }
}

// pad [nr] left with [nr].length - base [chr]'s (or '0')
function zeroPad(nr,base,chr){
   var  len = (String(base||10).length - String(nr).length)+1;
   return len > 0? new Array(len).join(chr||'0')+nr : nr;
}

// stop button handler
document.querySelector('#stop').onclick = function(){
    stopped = true;
    clearTimeout(0);
}

// start button handler
document.querySelector('#start').onclick = function(){
    stopped = true;
    clearTimeout(0);
    secondsAhead =...