我正在尝试为递归调用提供暂停和恢复功能。我正在使用“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