简体   繁体   English

闭包中的JavaScript For-loop alter loop语句

[英]JavaScript For-Loop alter loop statement in closure

I have a for-loop like this: 我有这样一个for循环:

for (var i = 0, ii = 10; i < ii; i++) {
    var timer = setTimeout(function(i,timer) {
        return function() {
            clearTimeout(timer);
            if (condition) ii++;
        }
    }(i,timer), 1000);
}

What I am trying to do is increase the amount of times the for-loop is executed inside of the delayed closure in that for-loop. 我想做的是增加for循环在该for循环中延迟关闭内执行的次数。

The problem is that by the time that one of the 10 timer functions is executed, the loop has already finished. 问题在于,当执行10个定时器功能之一时,循环已经完成。 (I assume this is the problem) (我认为这是问题所在)

I would like to know how I can alter ii within a such timeout function, without having to call the entire for-loop again. 我想知道如何在这样的timeout函数中更改ii ,而不必再次调用整个for循环。 (The process has to stay in one loop) (该过程必须保持一个循环)

You won't be able to do what you want exactly like that because whatever function is passed to setTimeout won't execute until the current function completes. 您将无法完全按照自己的意愿进行操作,因为传递给setTimeout任何函数都不会执行,直到当前函数完成为止。 For example, if you try: 例如,如果您尝试:

setTimeout(function() {
    console.log('Hello!');
}, 100);
while (true) { }

You'll never see 'Hello!' 您永远不会看到'Hello!' because the current function will never complete. 因为当前功能将永远无法完成。 Instead, you might consider creating a function such that it acts upon something given your ii variable. 相反,您可以考虑创建一个函数,使其对给定ii变量的东西起作用。

function doStuff(ii) {
    // Do some stuff given ii
    if (condition) {
        setTimeout(function() {
            doStuff(ii + 1);
        }, 1000);
    }
}

for (var i = 0; i < 10; i++) {
    doStuff(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM