the_darkside - 1 year ago 107
Javascript Question

# Combining for loop with setInterval()

My objective is to log each of the coordinate pairs to the console in the

`coords`
variable in succession every 5 seconds. I am able to do this with every pair in
`coords`
all at once with the
`setInterval()`
function, but how would I log
`coords[0]`
at 5 seconds,
`coords[1]`
at 10 seconds,
`coords[2`
] at 15 seconds, and so on - and then start over when finished?

``````coords = [[ -122.68181, 45.523713333333333 ], [ -122.681848333333363, 45.52369833333335 ],
[ -122.681996666666691, 45.523683333333338 ], [ -122.682078333333351, 45.523733333333332 ],
[ -122.681916666666694, 45.523736666666665 ], [ -122.6815766666667, 45.523753333333346 ],
[ -122.68182333333M3355, 45.523741666666659 ], [ -122.681823333333355, 45.523753333333339 ],
[ -122.681656666666683, 45.52375 ], [ -122.68162833333335, 45.523738333333334 ], [ -122.681936666666701, 45.52373 ]]

function listCoords() {
for (var i=0, l=coords.length; i<l; i++) {
console.log(coords[i])
}
}

setInterval(function(){
listCoords()
}, 5000);
``````

``````var i=0;
function listCoords() {
console.log(coords[i])
i=(i+1)%coords.length;
}

setInterval(listCoords,5000);
``````

Simply keep a global variable which stores the position to show next. If the function gets called, show this value, increase i and prevent that it jumps outside of the arrays bounds. This works like this:

imagine an array length of 3, itll do

``````0
(0+1)%3 = 1
(1+1)%3 = 2
(2+1)%3 = 0 // the loop starts again
``````

Alternatively use some pseudo recursion and timeouts:

``````;/*a semicolon, just for Andy ;) */
(function next(i){
console.log(coords[i]);
setTimeout(next,5000,(i+1)%coords.length);// show next one in 5 secs