I wrote a short program for my exercise routine. It takes a JSON array of exercise names and duration (seconds) and puts it on the screen. The JSON looks like this:
var exerciseArray = [
{
"desc": "Pushup/Pullup",
"countdown": 30
}, {
"desc": "Squat punch",
"countdown": 45
}, {
"desc": "Jumping jacks",
"countdown": 60
}
];
The function works, but it seems to be to be kind of a kludge. My problem was that I couldn't figure out how work with setInterval to iterate through the list of exercises (exerciseArray). What I did in the end is just decrement the countdown value, and when it's zero, move to the next item in exerciseArray (i++;). When I hit the end of the array — as measured by i and exerciseArray.length — I just run clearInterval and I'm done. Code below (I removed some of the extraneous stuff that just updates the HTML with the number of seconds, you can see the full thing on github):
function exerciseTimer(exerciseArray) {
var i = 0;
var exerciseObject = exerciseArray[i];
// do stuff
var tt = setInterval(function() {
var exerciseObject = exerciseArray[i];
// write html to the page
exerciseObject.countdown = exerciseObject.countdown - 1;
if (exerciseObject.countdown <= 0) {
if(i < (exerciseArray.length - 1)) {
i++;
} else {
clearInterval(tt);
}
}
}, 100);
}
My question is, what is the appropriate way to iterate while using setInterval? Is there a cleaner way? This feels very ugly to me.