Display array elements with delay

前端 未结 8 2001
星月不相逢
星月不相逢 2021-01-06 18:50

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++)
  {
          


        
8条回答
  •  旧时难觅i
    2021-01-06 18:56

    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/

提交回复
热议问题