for循环 setinterval_如何在for循环中使用setInterval函数

I'm trying to run multiple timers given a variable list of items. The code looks something like this:

var list = Array(...);

for(var x in list){

setInterval(function(){

list[x] += 10;

console.log(x + "=>" + list[x] + "\n");

}, 5 * 1000);

}

The problem with the above code is that the only value being updated is the item at the end of the list, multiplied by the number of items in the list.

Can anyone offer a solution and some explanation so I know why it's behaving this way?

解决方案

So, a few things:

Most importantly, the callback function you've passed to setInterval() maintains a reference to x rather than the snapshot value of x as it existed during each particular iteration. So, as x is changed in the loop, it's updated within each of the callback functions as well.

Additionally, for...in is used to enumerate object properties and can behave unexpectedly when used on arrays.

What's more, I suspect you really want setTimeout() rather than setInterval().

You can pass arguments to your callback function by supplying additional arguments to setTimout():

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

Here's an example:

var list = [1,2,3,4];

for (var x = 0, ln = list.length; x < ln; x++) {

setTimeout(function(y) {

console.log("%d => %d", y, list[y] += 10);

}, x * 500, x); // we're passing x

}

Luckily, numbers get passed by value rather than reference.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值