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!

5 Answers 5

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)

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
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?
@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.
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);
}

Comments

1

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

Comments

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();
  }
});

Comments

-2
var x = true;
while(x){
   console.log("In loop")
}

1 Comment

And what about the delay ? The while true is already in the question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.