简体   繁体   中英

Chrome setTimeout() timing issues

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?

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);
  }
 })

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM