Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot clear Interval within if query

I am learning about the setInterval and clearInterval method and meanwhile there appeared some problems with my learning process. In the code below you can see the function countdown which is including the var y which should be increased after every 500 milliseconds. If the var y reaches the value 3 the Interval should be cleared. But my code is not working like I actually want. What I am doing wrong?

  let y = 1
function countdown() {
    
    y += 0.5
    console.log(y)
}

const timerId = setInterval(countdown, 500)

if( y > 3) {
    clearInterval(timerId);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to put the ( y > 3) check within the countdown function. Currently it’ll only be executed once, and at the end.

Here’s a working example:

let y = 1;

const countdown = () => {
  y += 0.5;
  console.log(y);
  if( y >= 3) {
    clearInterval(timerId);
  }
}

const timerId = setInterval(countdown, 500);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading