简体   繁体   English

使用超时在React中无限循环

[英]Infinite for loop in React using timeout

I do have this function that print values of urls array, the first thing I want to do is run the forloop indefinitely and the second thing I don't understand why the 'done' console log is executed before the for loop: 我确实有此功能可以打印urls数组的值,我想做的第一件事是无限期地运行forloop,第二件事我不明白为什么在do循环之前执行“ done”控制台日志:

loop = () => {
        for (var i = 0; i < urls.length; i++) {
            (function(index) {
                setTimeout(function() {
                    console.log(urls[index]);
                }, i * 1000);
            })(i);
        }
        console.log('done');        
};

I tried wrapping this function inside another forloop but I got (in this example) 3 values each time, which is not my goal, I just need to repeat the loop. 我尝试将此函数包装在另一个forloop中,但每次(在此示例中)我都有3个值,这不是我的目标,我只需要重复循环即可。

for (var a = 1; a <= 3; a++) {
  setTimeout(() => this.loop(), 21000);
}

// Not working ( the urls.length = 21 so that's exactly 21 seconds )

while (true) {
  setTimeout(() => this.loop(), 21000);
}

// Freeze too much ram

Please someone suggest a better approach or help m solve the logic behind this 请有人提出更好的方法或帮助m解决其背后的逻辑

setTimeout doesn't block, it basically schedule the log call for i seconds in the future, that's why the "done" message is printed because all the scheduling has been finished, not the actually print url call. setTimeout不会阻塞,它基本上在将来安排i秒钟的日志调用,这就是为什么打印“ done”消息的原因,因为所有的调度都已经完成,而不是实际的打印url调用。

I don't really understand what you want to do but I guess this is pretty close: 我不太了解您要做什么,但是我想这很接近:

const printUrl = j => {
  console.log(urls[j])
  setTimeout(() => printUrl(j + 1), j * 1000)
}
printUrl(1)

setInterval with correct timeout solve the issue: 具有正确超时的setInterval解决问题:

loop = () => {
        for (var i = 0; i < urls.length; i++) {
            (function(index) {
                setTimeout(function() {
                    this.setState({ img: urls[index] });
                }, i * 500);
            })(i);
        }
};

svg = e => {
    this.setState({ anim: true, form: true });
     this.loop();
        setInterval(() => this.loop(), 10000);
};

urls.length = 20 urls.length = 20

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

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