Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an infinite loop in NodeJS

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!

like image 465
Ardzii Avatar asked Aug 06 '17 11:08

Ardzii


2 Answers

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)
like image 182
baao Avatar answered Sep 28 '22 06:09

baao


The function you're looking for is setInterval, to use like this: setInterval(callback, millis)

like image 44
Serge Kireev Avatar answered Sep 28 '22 05:09

Serge Kireev