简体   繁体   English

Chrome setTimeout()计时问题

[英]Chrome setTimeout() timing issues

I have a simple countdown script ( jsFiddle ). 我有一个简单的倒计时脚本( 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. 由于某种原因,如果我在Chrome中运行它并专注于其他选项卡,则计时器要比它慢了两倍...因此,当我同时在手机上运行独立计时器时,计时器运行正常,用我的计时器将焦点移回到选项卡上,它显示还剩约30秒。 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. 在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. 问题是您设置了太多setTimeout函数,时间= 60,有60个setTimeouts,因此它们会损害您的性能。 You can use setInterval instead: 您可以改用setInterval:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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