The following snippet uses a helper function to create the timers. This helper function accepts a loop counter argument i
and calls itself at the end of the timer handler for the next iteration.
function animateGraph() {
var graph;
setTimeMarkDelayed(0);
function setTimeMarkDelayed(i) {
setTimeout(function() {
document.getElementById("timeMark").innerHTML = phoneX[i].epoch;
if (i < 10) {
setTimeMarkDelayed(++i);
}
}, 3000);
}
}
You actually need some sort of helper function, otherwise you'll end up overwriting the value of i
in your for loop in every iteration and by the time your timers run out, i
will already be 9
and all handlers will act on the last element in phoneX
. By passing i
as an argument to the helper function, the value is stored in the local scope of that function and won't get overwritten.
Or you could use setInterval
like Radu suggested, both approaches will work.