2016-08-11 322 views
0

我想破解在頁面加載時啓動的setTimeout函數。所以我在這裏做的是,如果我點擊按鈕,然後我將flag值設置爲true,並且setTimeout應該打破,而這不會發生在這裏。 這個setTimeout函數在每個循環內部。以下是我的代碼。在foreach循環中打破setTimeout函數

   rData[0].dt.forEach(function(d, i) { 
        setTimeout(function() { 
         if(flag === "false"){ 
          console.log(flag); 
          reserRadius(i); //here I am changing radius of circle 
         }else{ 
          console.log(flag); 
          clearTimeout(); 
          return; 
         } 

        }, i * 2000); 
       }); 
+0

'clearTimeout'預計從'setTimeout'返回的ID,但如果你擁有了它沒有任何意義,因爲時間的函數被評爲超時已經完成,沒有理由調用'clearTimeout' –

+4

目前還不清楚你確實想要你的代碼做什麼。你不能刪除自己內部的'timeout',因爲它在執行時已經被刪除了。在你的問題中發佈一個[JSFiddle](https://jsfiddle.net/)片段會很有用。 – 2016-08-11 20:04:10

+0

我有這個setTimeout函數裏面運行的動畫代碼。如果我將鼠標懸停在特定區域上,我希望這個動畫停止,所以我正試圖在按鈕的幫助下停止它。 – shanky

回答

2

不是一次性創建所有超時,而只是在需要時創建它們。這樣,您就不必清除任何人,當你已經確定停止:

(function repeat(list, i) { 
    if (i >= list.length) return; // nothing (more) to do 
    var d = list[i]; // do you need d at all?? 
    setTimeout(function() { 
     if(flag === "false"){ 
      console.log(flag); 
      reserRadius(i); //here I am changing radius of circle 
      repeat(list, i+1); // schedule next timeout only now. 
     }else{ 
      console.log(flag); 
      // Don't schedule next timeout. This breaks the "loop". 
     } 
    }, 2000); // trigger 2 seconds from now. Note: no multiplying anymore. 
})(rData[0].dt, 0); // pass initial values: the array and index. 

在你的代碼版本,你就必須保持ID所有setTimeout調用返回值,和然後將它們全部(或至少剩下的)全部傳遞給clearTimeout。這會讓你的代碼非常麻煩。我認爲上述是一種更有效的方法。

0

setTimeout無法從其回調本身停止。 setTimeout 返回一個可以傳遞給clearTimeout的timeoutId,然後 停止該特定計時器。

停止所有這些定時器的一種方法是創建一個timeoutIds數組並進行如下更改。

var timerIds = []; 
rData[0].dt.forEach(function(d, i) { 
    timerIds.push(setTimeout(function(){ 
     if(flag === "false"){ 
      console.log(flag); 
      reserRadius(i); //here I am changing radius of circle 
     } 
     else{ 
      console.log(flag); 
     } 
    }, i * 2000)); 
}); 

function stopTimeouts(){ 
    timerIds.forEach(function(id){ 
     clearTimeout(id); 
    } 
} 
function codeThatMightChangeFlag(callback) { 
    // do a bunch of stuff 
    if (condition happens to change flag value) { 
     // call the callback to notify other code 
     stopTimeouts(); 
    } 
} 

參見:Clear array of setTimeout'sJavascript - wait until flag=true