How to create an infinite loop in NodeJS
Asked Answered
R

5

10

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!

Rectum answered 6/8, 2017 at 11:45 Comment(0)
A
26

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)
Adonic answered 6/8, 2017 at 11:51 Comment(4)
Hey Baao! Thanks a lot for your answer! One quick question though: Why is it better to have function that calls itself back rather than a setInterval?Rectum
IMHO it's better controllable, @Ardzii In this case, you'll also have it more accurate, as the next timeout is scheduled only after the rest of the function is run.Adonic
Does anyone know if the first solution won't bloat the call stack, considering the recursion will never end? Is it safe to use? or every other week I will see the process crashing?Karajan
@ZzAntáres the accepted solution will not add to the stack. You can see this in action if you add a console.trace() inside the recurring function. You'll notice the stack does not grow. Do the same with a function that does not use setInterval nor setTimeout and you can see the stacktrace growing each iteration.Sturtevant
F
2

Use Promise and setTimeout.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let i = 0;
while(true){
    await sleep(3000);//3000ms
    i++;
    console.log('Infinite Loop Test n:', i);
}
Flaxseed answered 8/12, 2022 at 14:22 Comment(0)
C
1

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

Commendam answered 6/8, 2017 at 11:49 Comment(0)
M
1

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();
  }
});
Metalwork answered 25/7, 2021 at 11:39 Comment(0)
C
-2
var x = true;
while(x){
   console.log("In loop")
}
Cleocleobulus answered 3/4, 2020 at 19:53 Comment(1)
And what about the delay ? The while true is already in the question!Bjork

© 2022 - 2024 — McMap. All rights reserved.