简体   繁体   中英

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:

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.

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

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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