我正在嘗試爲遞歸調用提供暫停和恢復功能。我正在使用「setTimeout」和「clearTimeout」功能...爲javascript循環執行實現暫停和恢復機制
當用戶單擊「暫停」按鈕時,計時器被設置爲無限時間(儘可能最大)。當用戶點擊「恢復」按鈕時,超時應該通過「clearTimeout」呼叫清除。但超時從未被清除。我的錯誤是什麼?
預先感謝您..
HTML:
<button id="loop_controler">pause</button>
JS:
var array = [1,2,3,4,5,6,7];
var pause = false;
var timer;
function execute(array,i){
var pauseTime = 0;
if (pause){
pauseTime = 2147483647; //max value for timeout
}
timer = setTimeout(function(){ //set timer
setTimeout(function() {
alert(array[i]); //this timeout gives a constant delay
if (array.length > i) //(just to give enough time to users to click button)
execute(array,i+1);
}, 1000);
}, pauseTime);
console.log('set ' + timer);
}
$('document').ready(function(){
$('#loop_controler').click(function(){
if ($(this).text() == 'pause'){
pause = true;
$(this).text('resume');
} else {
clearTimeout(timer); //clear timer
console.log('clear ' + timer);
pause = false;
$(this).text('pause');
}
});
execute(array,0);
});
你爲什麼不清除超時,當用戶點擊暫停,而不是設置超時爲無窮大?然後在用戶點擊簡歷時重新開始。 – Barmar 2014-11-02 06:44:14
主要問題是,在清除超時之後,您沒有以正常超時重新啓動它。 – Barmar 2014-11-02 06:45:00
您需要'i'作爲全局變量,因此您可以在陣列中的當前位置重新啓動計時器。 – Barmar 2014-11-02 06:46:09