Search code examples
javascriptsettimeout

Display array elements with delay


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.


Solution

    1. your loop runs four times, not three
    2. setTimeout starts with a lower case s
    3. your delay should be 3000 for 3 seconds, not 2000
    4. your delay should be 3000 * i, not 3000 or they'll all fire at once
    5. you can't use loop variables inside an asynchronous callback without special precautions - the callbacks will all see the last value assigned to i, 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.

    See http://jsfiddle.net/alnitak/mHQVz/