5) { clearInterval(intervalId); } } let intervalId = setInte" /> 5) { clearInterval(intervalId); } } let intervalId = setInte" /> 5) { clearInterval(intervalId); } } let intervalId = setInte"/>

setInterval and clearInterval in javaScript

90 Views Asked by At

let count = 0;

function printCount() {
  console.log("Count:", count);
  count++;

  if (count > 5) {
    clearInterval(intervalId);
  }
}

let intervalId = setInterval(printCount, 1000); clearInterval(intervalId);

I do not understand why its not working on Google Chrome console. Can you help me please?

2

There are 2 best solutions below

0
이명주 On

clearInterval is executed right after setInterval. Below may be work

let count = 0;

function printCount() {
  console.log("Count:", count);
  count++;

  if (count > 5) {
    clearInterval(intervalId);
  }
}

let intervalId = setInterval(printCount, 1000);
0
Jaykant On

The clearInterval(intervalId); line is placed right after the setInterval function, so it clears the interval immediately after setting it.

Try removing the clearInterval(intervalId); line outside of the setInterval call, and it should work as expected:

let count = 0;

function printCount() {
  console.log("Count:", count);
  count++;

  if (count > 5) {
    clearInterval(intervalId);
  }
}

let intervalId = setInterval(printCount, 1000);
// clearInterval(intervalId); // Remove this line

Now, the interval should continue running until the count is greater than 5.