2013-08-26 25 views
0

我想執行一段任意代碼,並且能夠隨時停止它。我想我可以用setTimeout做到這一點,然後用clearTimeout來阻止它。但是,如果超時中的代碼創建它自己的超時時間,那麼即使在我清除原始數據後,這些代碼仍會繼續執行。在Javascript中停止嵌套超時

例子:

var timeoutID = setTimeout(
    function(){ 
     console.log("first event can be stopped with clearTimout(timeoutID)"); 
     setTimeout(function(){console.log("but not this one")}, 5000) 
    }, 5000) 

現在,一個辦法是控制正在執行的代碼,並使其成爲任何額外的超時值存儲到一個全局變量和清除它們的一次。但有沒有更好的方法來做到這一點?有沒有辦法在任意代碼上做到這一點?

爲了澄清,我想能夠執行我想要的任何功能,那麼停止它時,我想,即使該函數包含超時

+1

請澄清一下你的問題你想要做什麼? –

+0

@tryingToGetProgrammingStraight我想執行任何函數,並且能夠在任何時候阻止它執行,即使函數使用它自己的超時。 – Houshalter

+0

請編輯你的問題 –

回答

3

你可以把內超時到一個變量太多:

var innerTimeout, 
    timeoutID = setTimeout(
    function(){ 
     console.log("first event can be stopped with clearTimout(timeoutID)"); 
     innerTimeout = setTimeout(function(){console.log("but not this one")}, 5000); 
    }, 5000); 
+0

他肯定也應該 – mplungjan

+0

爲什麼不重新使用timeoutID?第一次超時完成將開始第二次。 OP只是想取消整個事情的情況下,你可以使用timeoutID來清除它。 – HMR

+0

@HMR如果不會有重疊的呼叫,重用是好的。有了兩個變量,你可以更好地控制觸發超時。 – Teemu

1

你必須創建超時的ID,如該數組:

var timeoutIds = []; 

timeoutIds.push(setTimeout(
    function(){ 
    console.log("first event can be stopped with clearTimout(timeoutID)"); 
    timeoutIds.push(setTimeout(function(){console.log("but not this one")}, 5000)); 
}, 5000)) 

然後清除:

for (int i = 0; i < timeoutIds.length; i++) 
{ 
    clearTimeout(timeoutIds[i]); 
} 

timeoutIds = []; 
+0

沒有必要,因爲當第一個完成時第二個超時運行,那時清除第一個超時是沒有意義的。如果設置了多個超時,那麼可以使用一個數組,但在這種情況下,第二個超時由第一個超時開始,因此OP可以重新使用timeoutID – HMR

0

您可以將超時值包裝在一個對象中,或者將timeoutID用於第二次超時。

包裹在一個對象:

function Timer(){ 
    var me=this; 
    this.currentTimerID=setTimeout(function(){ 
    console.log("First timeout"); 
    me.currentTimerID=setTimeout(function(){ 
     console.log("Second timeout"); 
    },100); 
    },100); 
}; 
Timer.prototype.cancel=function(){ 
    clearTimeout(this.currentTimerID); 
}; 

var t = new Timer();//let this run it's course 
setTimeout(function(){t = new Timer()},250);//start timer again 
setTimeout(function(){t.cancel();},400);// cancel it after the first timeout 

再使用timeoutID:

var timeoutID = setTimeout(
    function(){ 
     console.log("first event can be stopped with clearTimout(timeoutID)"); 
     timeoutID=setTimeout(function(){console.log("but not this one")}, 100) 
    }, 100) 
setTimeout(function(){ 
    clearTimeout(timeoutID); 
},150);// will not execute the second timeout 

一個建議:如果你使用的超時測試代碼,然後不要用這麼高的價值,因爲它會花10秒讓您的原始代碼運行。