I'm stuck looking for the right way to stop a setTimeout call recursive function. I want to be able to restart an animation without having to wait for the animation to finish.
Any help would be awesome!!
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