I have an arrays=[John; Alex; Mark]
, I wanna to show the elements of this array one by one by 3 second delay.
for (var i=0; i<=3; i++)
{
setTimeout(function(){x.innerHTML=s[i]},3000)
}
It seems very simple problem, but I can't figure out.
setTimeout
starts with a lower case s
3000 * i
, not 3000
or they'll all fire at oncei
, not the values it had as you went through the loop.This works, and completely avoids the loop variable issue:
var s = ['John', 'Mark', 'Alex'];
var i = 0;
(function loop() {
x.innerHTML = s[i];
if (++i < s.length) {
setTimeout(loop, 3000); // call myself in 3 seconds time if required
}
})(); // above function expression is called immediately to start it off
Note how it uses "pseudo-recursion" to trigger the next iteration 3000ms after the completion of the previous iteration. This is preferable to having n
outstanding timers all waiting at the same time.