我一直在尋找正確的方法來停止setTimeout調用遞歸函數。我希望能夠重新開始動畫而不必等待動畫完成。如何在JavaScript中停止遞歸函數?
任何幫助將是真棒!
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>
退房['clearTimeout'(https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout) –
調用setTimeout的設置相同功能的新超時在技術上不是遞歸功能。 – GolezTrol
我有,但不認爲我正確實施它。我錯過了一些東西:( – bridgbro