1

I have a simple countdown script (jsFiddle).

var time = 60;
function countDown(timeLeft){
     $("#timeLeft").text(timeLeft);
    if(timeLeft!=0){
        setTimeout(function(){ countDown(--timeLeft); }, 1000);   
    }
}
countDown(time);

For some reason if I run it in Chrome and focus on a different tab, the timer is two times slower than it should be... So when I run an independent timer on my phone at the same time it goes of properly and when I focus back to the tab with my timer it shows ~30s left. It works just fine when the tab containing the script is in focus, it goeas extra slow only when it's open in background. It doesn't happen in Firefox. Is it some kind of a weird bug or am I doing something wrong?

Kuba Orlik
  • 3,360
  • 6
  • 34
  • 49

1 Answers1

1

The problem is you set too many setTimeout functions, with time = 60, there are 60 setTimeouts, so they harm your performance. You can use setInterval instead:

function countDown(timeLeft){
 var intervalProc = setInterval(function(){
  $("#timeLeft").text(timeLeft);
  timeLeft--;
  if(timeLeft <= 0){
   clearInterval(intervalProc);
  }
 })

}
Rikky
  • 515
  • 3
  • 8
  • 2
    Your solution helps, but only partially - the countdown is now ~1.5x slower instead of ~2 ([updated jsFiddle](http://jsfiddle.net/GZsah/2/)). I guess that for accurate measurments I will have to resort to answer from [this question](http://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome) – Kuba Orlik Jul 13 '13 at 12:26
  • Yes, you're right, I've just realized it! It's like the browser sucks with background loop. In addition, I try solve it with web worker in html5, it's run flawless :D – Rikky Jul 13 '13 at 12:35