Display array elements with delay

前端 未结 8 2000
星月不相逢
星月不相逢 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条回答
  •  轮回少年
    2021-01-06 19:04

    Your code won't work, since you set four timeouts of 2000 milliseconds (i.e. 2 seconds) at a time. You'd better use closure that sets three timeouts (by number of elements in array) with 3000 milliseconds of delay. It can be done with the following code (note that setTimeout is written from the small letter):

    var s = ["John", "Alex", "Mark"];
    for (var i = 0; i < s.length; i++) {
        (function(i) {
            setTimeout(function() {
                x.innerHTML = s[i];
            }, 3000 * i);
        })(i);
    }
    

    DEMO: http://jsfiddle.net/6Ne6z/

提交回复
热议问题