显示延迟的数组元素 [英] Display array elements with delay

查看:69
本文介绍了显示延迟的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 s = [John;亚历克斯; Mark] ,我想逐个延迟地显示这个数组的元素。

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似乎很简单的问题,但我想不出来。

It seems very simple problem, but I can't figure out.

推荐答案


  1. 你的循环运行四次,而不是三个

  2. setTimeout 以小写字母开头 s

  3. 你的延迟应该是3000秒3秒,而不是2000

  4. 你的延迟应该是 3000 * i ,而不是 3000 或者它们都会立即触发

  5. 如果没有特别的预防措施,你不能在异步回调中使用循环变量 - 回调将全部看到分配给 i 的最后一个值,而不是你经历循环时的值。

  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

注意它是如何使用伪递归的在上一次迭代完成后触发3000ms的下一次迭代。这比同时等待的 n 未结计时器更可取。

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.

参见 http://jsfiddle.net/alnitak/mHQVz/

这篇关于显示延迟的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆