我试图通过递归调用为循环提供暂停和恢复功能。我正在使用" setTimeout"和" clearTimeout"这个功能......
当用户点击按钮"暂停"时,定时器设置为无限时间(最大可能)。当用户点击按钮" resume"时,应该用" 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);
});
答案 0 :(得分:2)
早在2012年,我在JavaScript中为delta timing编写了一段代码,该代码使用setTimeout
并具有start
和stop
函数:https://gist.github.com/aaditmshah/2056987
参见演示:
var button = document.querySelector("button");
var div = document.querySelector("div");
var running = false;
var number = 1;
var timer = new DeltaTimer(function () {
div.innerHTML = number++;
}, 1000);
button.addEventListener("click", function () {
if (running) {
timer.stop();
button.innerHTML = "Start";
running = false;
} else {
timer.start();
button.innerHTML = "Stop";
running = true;
}
});
function DeltaTimer(render, interval) {
var timeout;
var lastTime;
this.start = start;
this.stop = stop;
function start() {
timeout = setTimeout(loop, 0);
lastTime = Date.now();
return lastTime;
}
function stop() {
clearTimeout(timeout);
return lastTime;
}
function loop() {
var thisTime = Date.now();
var deltaTime = thisTime - lastTime;
var delay = Math.max(interval - deltaTime, 0);
timeout = setTimeout(loop, delay);
lastTime = thisTime + delay;
render(thisTime);
}
}
<button>Start</button>
<div></div>
希望有所帮助。
答案 1 :(得分:1)
我误解了clearTimeout函数。我认为回调(setTimeout(...)中的回调)将在调用clearTimeout后立即执行。但是在调用clearTimeout之后没有执行回调...
正在运行的JS代码是
var array = [1,2,3,4,5,6,7];
var timer;
var i=0;
function execute(){
timer = setTimeout(function () {
alert(array[i]);
i++;
if (array.length > i){
execute();
}
}, 1000);
}
$('document').ready(function(){
$('#loop_controler').click(function(){
if ($(this).text() == 'pause'){
clearTimeout(timer);
$(this).text('resume');
} else {
execute();
$(this).text('pause');
}
});
execute(array,0);
});