Display array elements with delay

前端 未结 8 2042
星月不相逢
星月不相逢 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 18:57

    If you do not use closure, you will end up with i being undefined. This is because in each iteration you are overriding what i is. By the time it finishes, it will be undefined. Using a closure will preserve i.

    On another note, it's kind of pointless to hard code in values (i.e. i<3) when you can just check for length. This way, if s ever changes, you for loop will still grab everything.

    var s = ['john','mark','brian'];
    for (var i = 0; i < s.length; i++) {
        (function(i) {
            setTimeout(function() {
                x.innerHTML = s[i];
            }, 3000*(i+1));
        })(i);
    }
    

提交回复
热议问题