簡體   English   中英

Chrome setTimeout()計時問題

[英]Chrome setTimeout() timing issues

我有一個簡單的倒計時腳本( jsFiddle )。

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

由於某種原因,如果我在Chrome中運行它並專注於其他選項卡,則計時器要比它慢了兩倍...因此,當我同時在手機上運行獨立計時器時,計時器運行正常,用我的計時器將焦點移回到選項卡上,它顯示還剩約30秒。 當包含腳本的選項卡處於焦點位置時,它工作得很好,只有在后台打開時,它的運行速度才特別慢。 在Firefox中不會發生這種情況。 是某種奇怪的錯誤還是我做錯了什么?

問題是您設置了太多setTimeout函數,時間= 60,有60個setTimeouts,因此它們會損害您的性能。 您可以改用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