I've seen a bunch of answers on JS about an infinite loop and I thought that it would help for my code but it doesn't seem to be working properly. I have that:
var i = 0
while (true) {
setTimeout(() => {
i ++
console.log('Infinite Loop Test n:', i);
}, 2000)
}
The objective is to get the log every 2 seconds within an infinite loop but I can't seem to be getting anything back... Where am I mistaken?
Thanks in advance for your help as usual!
Why do you want a while loop at all? Either use setInterval
, or (better) create a function that calls itself again after a timeout:
function logEvery2Seconds(i) {
setTimeout(() => {
console.log('Infinite Loop Test n:', i);
logEvery2Seconds(++i);
}, 2000)
}
logEvery2Seconds(0);
let i = 0;
setInterval(() => {
console.log('Infinite Loop Test interval n:', i++);
}, 2000)
The function you're looking for is setInterval, to use like this:
setInterval(callback, millis)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With