The Situation
I have a function which is called on button click and which should draw an animated chart, updating the chart every 2 seconds. When the user clicks that button again, while the animation is still running, the animation should stop.
My current solution
Right now I have the following script which stops the animation visually, but the underlying for-loop continues until the end in the background:
var animRun = false;
$("#animateButton").on("click", function() {
if (animRun === false) {
redraw(data.slice(0,30))
//some CSS...
} else {
//Some CSS...
animRun = false;
}
});
function redraw(data) {
animRun = true;
for (var i=0; i<data.length;i++){
(function(i){
setTimeout(function(){
if(animRun === true) {
//draw the chart
return draw(data[i])
}
},2000*(i))
if (i === data.length -1) {
//reset animRun
if(animRun === true) {
//Some CSS things
//...
animRun = false;
}
}
})(i);
}
}
Question
What would be the correct way of stopping the for-loop when the user clicks the button again while the animation is still executing?
animRunis set tofalseon the second click, thus thedraw()function is not executed