2017-03-21 36 views
-3

據我所知,我們可以clearInterval爲:如何清除分配給相同變量的兩個setIntervals?

var go = setInterval(function() { 
 
    console.log("go"); 
 
}, 5000); 
 

 
clearInterval(go);

但由於某種原因,在我的javascript代碼我有相同的變量被分配兩個時間中的setInterval。現在即使我多次清除它也不會被清除。例如:

var go = setInterval(function(){ 
 
    console.log("go"); 
 
}, 1000); 
 

 
var go = setInterval(function(){ 
 
    console.log("go"); 
 
}, 1000); 
 

 
clearInterval(go); 
 
clearInterval(go); 
 

 
clearInterval(go); 
 
clearInterval(go);

我的問題是:

這到底是怎麼回事? javascript如何處理這種情況? go有什麼不對?爲什麼不清除?

+2

你不能。您已覆蓋以前的計時器ID。它丟失了。 – Bergi

+1

它不是如果你清除它,它會指向你的第一個 – mehulmpt

+1

相關:'const'會阻止你爲你的響應重新分配'intervalId' – naomik

回答

1

正如一些評論所提到的,你所做的是重新分配您的go變量。每次撥打setInterval時都會返回一個不同的ID。一旦重新分配了引用該值的唯一變量,以前的值就會丟失。

當涉及到唯一標識符時,它會打電話來保留它們的可擴展列表,這樣您就不會丟失該進程的標識符。我建議做一個數組,推動每一個新的ID給它(使用它很像一個棧),這樣,他們都在同一個地方,但仍然能夠被單獨引用:

var intervalIDs = []; //we would want something like this to be a global variable 
//adding IDs to the array: 
intervalIDs.push(window.setInterval(function(){console.log("go 1");}, 1000)); 
intervalIDs.push(window.setInterval(function(){console.log("go 2");}, 1000)); 
//now we know we can find both IDs in the future 
//clearing an interval: 
window.clearInterval(intervalIDs.pop()); //takes the last ID out of the array and uses it to stop that interval. this could be done in a for loop to clear every one you've set using the above method. 
//OR if you happen to know the index (in the array) of a specific interval id you want to clear: 
var index = /*index number*/; 
window.clearInterval(intervalIDs.splice(index, 1)[0]); 

的一點是要確保你保持引用你的時間間隔的手段(或其他任何相似的行爲)。

1

你不能。您已覆蓋以前的計時器ID。它丟失了。

無論你多久打電話給clearInterval,只有當前存儲在變量中的第二個區間將被清除。

您需要多個變量(或定時器的數據結構,例如數組):

var go1 = setInterval(function(){ 
    console.log("go 1"); 
}, 1000); 

var go2 = setInterval(function(){ 
    console.log("go 2"); 
}, 1000); 

clearInterval(go1); 
clearInterval(go1); // nothing will happen 
clearInterval(go2); 
+0

Thanx。 javascript存儲'go'的前一個實例在哪裏? JavaScript引擎是否將堆棧中的兩個空格分配給'go'? – user31782

+0

沒有「以前的例子」。只有一個空間,並且變量被寫入前一個值時不再存儲。 – Bergi