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);
}
CodePudding user response:
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);