Attempting to build a chart that allows users to click play and it will cycle through an array of years, displaying each year in the chart for a few seconds, before moving onto the next.
It should also allow the user to click pause, pausing the animation; this is where I am failing.
I'm fairly certain my issue is scoping, but not 100%; I've got it to where the animation will cycle through, however when the user clicks pause, it continues to cycle through, not putting the animation on pause. I can see the clearInterval is firing off in console.log, but again, it does nothing and the animation continues.
I'm using setTimeout to delay each charts' appearance and using (most certainly in the wrong manner) setInterval to schedule the loop. I've read/tried a number of answers here dealing with setTimeout and setInterval, but to no avail. I'm positive it is my lack of understanding why they don't work and not that my question "is different" from the others.
That said, I've been banging my head on my desk for three days now and could really use some pointers here. Below is the JavaScript/jQuery that I'm currently working with:
jQuery('#animation-play').on('click', function() {
// loopThroughYears();
var animation;
if (jQuery('#animation-play').hasClass('play')) {
jQuery('#animation-play').addClass('stop').removeClass('play').text('Pause Animation');
var years = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015];
var time = 1000;
if (animation) {
clearInterval(animation);
}
animation = setInterval(function() {
$.each(years, function(index, values) {
setTimeout(function() {
if (years.this < 2016) {
selectChartYear(values);
jQuery("#chart-years").val(values);
}
}, time);
});
}, time);
} else {
jQuery('#animation-play').addClass('play').removeClass('stop').text('Play Animation');
console.log("Timeout Cleared!");
clearInterval(animation);
}
});
The
animationvariable is declared inside the click handler, creating a new one every time a click happens.You'd have to store that variable somewhere else, for instance on the element with jQuery's
data()