How to create an infinite loop in NodeJS

Viewed 28898

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!

4 Answers

Here is an example of TypeScript implementation and usage:

interface ILoopContext<T> {
  data: T;
  state: "RUNNING" | "PAUSED";
}

function loop<T>(
  interval: number,
  context: ILoopContext<T>,
  func: (options: { data: T; start: () => void; stop: () => void }) => void
) {
  const stop = () => context.state = "PAUSED";
  const start = () => context.state = "RUNNING";

  setTimeout(() => {
    if (context.state === "RUNNING") {
      func({ data: context.data, start, stop });
    }

    loop(interval, context, func);
  }, interval);

  return { start, stop };
}

loop(1000, { state: "RUNNING", data: { counter: 0 } }, (options) => {
  const { stop, data } = options;
  data.counter += 1;
  console.log(data.counter);
  if (data.counter == 10) {
    stop();
  }
});
var x = true;
while(x){
   console.log("In loop")
}
Related