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

发布于 2024-12-09 13:45:52 字数 320 浏览 0 评论 0原文

我正在尝试在给定可变项目列表的情况下运行多个计时器。代码看起来像这样:

var list = Array(...);

for(var x in list){
    setInterval(function(){
        list[x] += 10;
        console.log(x + "=>" + list[x] + "\n");
    }, 5 * 1000);
}

上面代码的问题是,唯一被更新的值是列表末尾的项目乘以列表中的项目数。

任何人都可以提供解决方案和一些解释,以便我知道为什么会出现这种情况?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

奢华的一滴泪 2024-12-16 13:45:52
var list = [1, 2, 3, 4, 5];

for (var i = 0, len = list.length; i < len; i += 1) {
    (function(i) {
        setInterval(function() {
            list[i] += 10;
            console.log(i + "=>" + list[i] + "\n");
        }, 5000)
    })(i);
}

这是工作代码:

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

for (var i = 0, len = list.length; i < len; i += 1) {
    (function(i) {
        setInterval(function() {
            list[i] += 10;
            console.log(i + "=>" + list[i] + "\n");
        }, 5000)
    })(i);
}

这里索引 i 存储在匿名函数中,以便它不会被连续循环覆盖。代码中的 setInterval 函数仅保留对 i 最后一个值的引用。

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

for (var i = 0, len = list.length; i < len; i += 1) {
    (function(i) {
        setInterval(function() {
            list[i] += 10;
            console.log(i + "=>" + list[i] + "\n");
        }, 5000)
    })(i);
}

Here is the working code:

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

for (var i = 0, len = list.length; i < len; i += 1) {
    (function(i) {
        setInterval(function() {
            list[i] += 10;
            console.log(i + "=>" + list[i] + "\n");
        }, 5000)
    })(i);
}

Here the index i is stored in an anonymous function, so that it is not overwritten by consecutive loops. setInterval function in your code keeps the reference only to the last value of i.

当梦初醒 2024-12-16 13:45:52

因此,有几点:

  1. 最重要的是,您传递给 setInterval() 的回调函数维护对 x 的引用,而不是 x< 的快照值/code> 因为它在每个特定迭代期间都存在。因此,当 x 在循环中发生更改时,它也会在每个回调函数中更新。
  2. 此外,for... in 用于枚举对象属性,并且在数组上使用时可能表现异常
  3. 更重要的是,我怀疑你真的想要 setTimeout() 而不是 setInterval()

您可以通过向 setTimout() 提供附加参数来将参数传递给回调函数:

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

数字将按值而不是引用传递。这是一个例子:

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
}

So, a few things:

  1. 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.
  2. Additionally, for...in is used to enumerate object properties and can behave unexpectedly when used on arrays.
  3. 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, ...]);

Numbers will be passed by value rather than reference. 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
}

鹿童谣 2024-12-16 13:45:52

您可以结合使用 forEachsetTimeout 以按时间间隔循环遍历数组。

let modes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let interval = 1000; //one second
modes.forEach((mode, index) => {

  setTimeout(() => {
    console.log(mode)
  }, index * interval)
})

You can combine forEach and setTimeout to loop over the array with the interval.

let modes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let interval = 1000; //one second
modes.forEach((mode, index) => {

  setTimeout(() => {
    console.log(mode)
  }, index * interval)
})

夜无邪 2024-12-16 13:45:52

您不必将 for 循环与 setInterval 语句一起使用。试试这个:

var list = Array(...);
var x = 0;

setInterval(function() {

    if (x < list.length;) {
        list[x] += 10;
        console.log(x+"=>"+list[x]);
    }

    else return;

    x++;
}, 5000);

You don't have to use a for cycle with the setInterval statement. Try this:

var list = Array(...);
var x = 0;

setInterval(function() {

    if (x < list.length;) {
        list[x] += 10;
        console.log(x+"=>"+list[x]);
    }

    else return;

    x++;
}, 5000);
梦魇绽荼蘼 2024-12-16 13:45:52

我不知道如何使用 for 循环执行此操作,但这里的代码将按时间间隔打印出数组中的每个元素:

function displayText(str) {
   $('.demo').append($('<div>').text(str));
}
var i = 0;

var a = [12, 3, 45, 6, 7, 10];

function timedLoop() {
setTimeout(function () {
    displayText(a[i]);
    i++;
    if(i < a.length) {
        timedLoop();
    }
}, 2000)
}

timedLoop();

使用一些 jquery 在浏览器中显示它。

I don't know how to do this with a for loop but this code here will print out each element in an array at timed intervals:

function displayText(str) {
   $('.demo').append($('<div>').text(str));
}
var i = 0;

var a = [12, 3, 45, 6, 7, 10];

function timedLoop() {
setTimeout(function () {
    displayText(a[i]);
    i++;
    if(i < a.length) {
        timedLoop();
    }
}, 2000)
}

timedLoop();

Using a bit of jquery to show it in the browser.

久光 2024-12-16 13:45:52

请看看这个最简单的解决方案。它也适用于 forloop。它看起来像一个间隔,但它是每次迭代增加的超时。对于每次迭代,setTimeout 都会加倍。

for(let i=1; i<=10;i++){
    setTimeout(function(){
        console.log(i)
    },i*1000)
}

Please look at this simplest solution. It does work with forloop too. It looks like an interval but it is a timeout increased for each iteration. For each iteration setTimeout doubles.

for(let i=1; i<=10;i++){
    setTimeout(function(){
        console.log(i)
    },i*1000)
}

心如荒岛 2024-12-16 13:45:52

如果你有 JSON 数组和 jQuery,你可以使用:

$.each(jsonArray, function(i, obj) {
    setInterval( function() {
        console.log(i+' '+obj);
    }, 10);
});

If you have JSON array and jQuery included, you can use:

$.each(jsonArray, function(i, obj) {
    setInterval( function() {
        console.log(i+' '+obj);
    }, 10);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文