为什么 javascript setTimeout() 不能循环工作? [英] why does javascript setTimeout() not work in a loop?

查看:73
本文介绍了为什么 javascript setTimeout() 不能循环工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

<!DOCTYPE html>
<html>
<head>
<script>
function timedText()
{
  var x=document.getElementById('txt');
  var t = new Array();
  t[1] = setTimeout( function(){x.value="2 seconds"}, 2000 );
  t[2] = setTimeout( function(){x.value="4 seconds"}, 4000 );
  t[3] = setTimeout( function(){x.value="6 seconds"}, 6000 );
}
function timedTextArr()
{
  var x=document.getElementById('txt');
  var t = new Array();
  for( var i = 0 ; i < 3 ; i++ ) {
    t[i] = setTimeout( function(){x.value=i*2+" seconds"}, i*2000 );
  }
}
</script>
</head>
<body>
<form>
<input type="text" id="txt" />
<input type="button" value="Display timed text!" onclick="timedText()" />
<input type="button" value="Display timed text Arr!" onclick="timedTextArr()" />
</form>
<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>
</html>

函数 timedText() 有效,但 timedTextArr() 无效.这两个函数都将 setTimeout() 的返回值分配给数组元素.但是在 for() 循环中,只有最后一个计时器起作用……而且它起作用了 3 次.

Function timedText() works, but timedTextArr() doesn't. Both functions assign return values from setTimeout() to array elements. But in the for() loop, only the last timer works... and it works three times.

这是一个错误吗?

推荐答案

这不是 bug,看看 Javascript 中的闭包是什么.

This is not a bug, have a look at what closures are in Javascript.

基本上在你的 for 循环函数中

Basically in your for loop the function

function(){x.value=i*2+" seconds"}

只看到" i 变量的一个实例.

only "sees" one instance of the i variable.

所以一旦循环结束,i 就等于 3,所以对于所有函数都是 3.

So once the loop is over, i is equal to 3, so it is 3 for all functions.

您需要将调用包装在另一个匿名函数中以创建作用域,如下所示:

You need to wrap the call in another anonymous function to create a scope, like this:

t[i] = setTimeout( (function(i){ return function(){x.value=i*2+" seconds"}})(i), i*2000 );

外层函数会创建一个新的作用域,在它内部,i 将等于循环中 i 的值并保持这样.你可以试试看:http://jsfiddle.net/6b68E/

The outer function will create a new scope, and inside it i will be equal to the value of i in the loop and stay like this. You can try it out there: http://jsfiddle.net/6b68E/

这篇关于为什么 javascript setTimeout() 不能循环工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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