如何在for ...循环中使用setTimeout [英] How to Use setTimeout in a for...loop

查看:65
本文介绍了如何在for ...循环中使用setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要的(新闻自动收录机类型的功能):

What I want is this (news ticker type functionality):

  1. 从ul标签获取li的列表
  2. 浏览所有li并获取文本
  3. 通过firefox console.log()在控制台中显示文本
  4. 获取下一个li,然后重复直到显示所有li

这是目标,但是setTimeout并未按照我的预期运行.仅显示LAST迭代(后四").那个(第四后")连续显示四次.

That's the goal, but setTimeout is not running as I thought it would. Only the LAST iteration ("Post Four") is showing. And that ("Post Four") is showing four times in a row.

<body>
<ul id="post_list">
 <li>Post One</li>
 <li>Post Two</li>
 <li>Post Three</li>
 <li>Post Four</li>
</ul>

<script type="text/javascript">
var ul = document.getElementById('post_list');
var li = ul.getElementsByTagName('li');

for(var x=0; x < li.length; x++){
    var li_text = li[x].childNodes[0].nodeValue;
    setTimeout(function(){showText(li_text)}, 1000);
}

function showText(text) {
    console.log(text);
}           
</script>
</body>

推荐答案

发生这种情况的原因是由于闭包.for循环块周围有闭包,因此当您引用"li_text"时,它始终等于li_text设置为的 last 值.for循环不会为循环中的每次迭代创建单独的闭包.

The reason this is happening is because of closures. The for loop block has closures around it, so when you reference 'li_text' it was always equal the last value that li_text was set to. The for loop does not create a separate closure for each iteration through the loop.

这篇关于如何在for ...循环中使用setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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