【发布时间】:2016-02-25 07:43:44
【问题描述】:
我一直在寻找停止 setTimeout 调用递归函数的正确方法。我希望能够重新启动动画而不必等待动画完成。
任何帮助都会很棒!
var viewArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var started = 0;
function animator() {
if (!started) {
console.log("Start... ");
started = 1;
var i = 0;
count = 1;
(function iterator() { // <-- how can I kill this iterator function when the user clicks stop
document.getElementById("output").innerHTML = viewArray[i];
if (++i < viewArray.length) {
setTimeout(iterator, 1000);
count++
if (count >= viewArray.length) {
started = 0;
} //when animation complete (number reaches 10) allow start animation button to work again
}
})();
} else {
console.log("Wait..."); // inactivate button
}
started = 1;
}
<div id="output" style="margin: 40px; font-size:130px"></div>
<div style="margin: 40px;">
<button id="on" onclick="animator();">Start Animation</button>
</div>
<div style="margin: 40px;">
<button id="off">Stop Animation</button>
</div>
【问题讨论】:
-
调用 setTimeout 为同一函数设置新的超时在技术上不是递归函数。
-
我有,但我认为我没有正确实施它。我错过了一些东西:(
-
在您的代码中没有调用 clearTimeout,所以是的,您遗漏了一些东西。 :) 您是否存储了 setTimeout 返回的计时器 ID,以便将其传递给 clearTimeout?
-
@GolezTrol - 函数使用 setTimeout 调用自身的技术术语是“recurse-ish”。
标签: javascript jquery animation recursion