0

I have a setInterval which is supposed to alert the amount of incremented a every 1 second only under a condition which is if a <= 5, else it should make return a = 1, which means it should turn a back to 1 and stop the setInterval from executing as initialized, but surprisingly it starts to execute the setInterval over and over again, each round with a = 1 incrementng.

I want the setInterval to be executed only if a <= 5 and as soon as this condition isn't true, then stop the setInterval and turn a back to 1, I don't want it to start the functoin over and over again, though it is turning a back to 1.

How can I make this happen?

function doSomething() {

  let a = 1;

  foo = setInterval(() => {

    if (a <= 5) {
      a++;
      console.log(a)
    } else {
      return a = 1;
    }

  }, 1000)

  return 0;

}
setTimeout(doSomething, 5000);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
christy
  • 3
  • 5
  • 4
    A `return` is meaningless inside a `setTimeout` or `setInterval` (other than terminating the current function call). It doesn’t return anywhere. You stop the interval by calling `clearInterval(foo);`. – Sebastian Simon May 04 '21 at 15:08
  • 1
    `return` just stops the current execution of a function. `setInteval` schedules regular executions. Use [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) with the interval ID to stop this schedule. – VLAZ May 04 '21 at 15:09
  • All of your function calls have a `return undefined` at the end implicitly. That doesn't stop the interval, and it might be intuitive to think returning truthy would, but that's not documented anywhere. – ggorlen May 04 '21 at 15:10

1 Answers1

1

This is because it runs every interval. return just stops that iteration.

const interval = setInterval(() => {
  console.log("Iterating")
}, 300)

setTimeout(() => {
  clearInterval(interval)
}, 900)
DecPK
  • 24,537
  • 6
  • 26
  • 42
R3FL3CT
  • 551
  • 3
  • 14