我正在尝试通过递归调用为循环提供暂停和恢复功能。我正在为此使用“setTimeout”和“clearTimeout”函数...
当用户单击“暂停”按钮时,计时器将设置为无限时间(可能的最大值)。当用户单击“恢复”按钮时,超时应该通过“clearTimeout”调用清除。但超时永远不会被清除。我的错误是什么?
先感谢您..
HTML:
<button id="loop_controler">pause</button>
Run Code Online (Sandbox Code Playgroud)
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'){ …Run Code Online (Sandbox Code Playgroud) javascript ×1