2013-03-14 146 views
1

當我們使用SetInterval返回的值調用clearInterval時,它是否使該值爲null或undefined。ClearInterval未清除SetInterval

我打電話給clearInterval來清除setInterval,但顯然setInterval的值保持不變,甚至在調用clearInterval後也不會改變。 t是否爲空或未定義?這裏是我的代碼片段

var setIntervalId; // declared in global scope 
//lined of code 

function autorefresh() { 
    if (statesCount > 0) { 
    setIntervalId = setInterval(function() { 
     //lines of code 
     // calling some handler 
    }, 30000); 
    } 

    if (statesCount === 0) { 
    clearInterval(setIntervalId); 
    } 
} 

正如你看到的,我打電話給我的每30秒setInterval函數,調用時首次分配一定的參考價值setIntervalId,但即使調用clearInterval後的值仍然存在。在調用clearInterval之後它應該變爲null還是undefined?如果它應該爲null或undefined我應該在這裏做什麼。我已經在全局範圍中定義了setIntervalId。

+2

你的代碼無效,將無法運行。 – 2013-03-14 15:41:06

回答

5

函數clearInterval不會清除傳入它的值。如果你想清除它,你必須做你自己

clearInterval(setIntervalId); 
setIntervalId = undefined; 

注意,它不會出現像你正確地守着最初的呼叫setInterval。這可能會導致呼叫進行多次,因此您有多個間隔設置。我想你應該增加自己的初始if塊以下

if (statesCount > 0 && typeof(setIntervalId) === 'undefined') { 
    ... 
} 
+0

感謝您清除我的困惑。我在想clearInterval會將setIntervalId的值重置爲undefined。手動額外檢查和重置可能會使其工作:) ..再次感謝 – 2013-03-16 08:56:25

3

它應該成爲null或undefined調用clearInterval後?

不,它只是一個數字。當間隔被清除後,這個數字只是一個歷史的好奇心。

如果您願意,您可以在將它用於clearInterval後明確指定undefined。除非您正在使用它來跟蹤您的功能是否正在定期運行,否則無需執行此操作。

0

如果當時只允許一個時間間隔,這應該可以正常工作。

如果您允許多個間隔,您需要維護對每個實例的訪問權限以阻止它們。

var setIntervalId; // declared in global scope 
var statesCount = 1; // simulate active state 
//lined of code 


function autorefresh() { 
    if (statesCount > 0) { 
    console.log('started'); 
    setIntervalId = setInterval(function() { 
     // just to see whats happening in console 
     console.log(statesCount); 

     // performe interval checks inside the interval loop not outside if you want to stop it automaticaly 
     if (statesCount === 0) { 
     clearInterval(setIntervalId); 
     } 
     // lines of code 
     // calling some handler 
    }, 1000); // repeat every 1s 
    }; 
} 

// run interval 
autorefresh(); 

// stimulate change of stateCount after 5s 
// setTimeout(function(){ 
// statesCount = 1; 
// },5000); 

// clear interval after 10s 
setTimeout(function(){ 
    clearInterval(setIntervalId); 
    console.log('stoped'); 
},10000);