Display array elements with delay

javascript, settimeout

Solution

- your loop runs four times, not three

- `setTimeout` starts with a lower case `s`

- your delay should be 3000 for 3 seconds, not 2000

- your delay should be `3000 * i`, not `3000` or they'll all fire at once

- 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/

Problem

I have an array`s=[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.

Original source

Related problems