Home > front end >  stop timer at 0 with javascript
stop timer at 0 with javascript

Time:01-10

i set a setinterval starting from 20 to 0. When the counter is smaller than or equal 10 i want the text to change to red (this works) but when it reaches 0 i want the counter to stop decreasing, but it doesn't. what am i doing wrong?

`let timerCount = document.querySelector('.imposters__voting span')
let counter = 20; 
setInterval(function(){
    if (counter > 11){
        counter--; 
    } else if(counter <= 10){
        counter--;
        document.querySelector('.imposters__voting').style.color = 'red'
    } else if(counter = 0){
        document.querySelector('.imposters__voting').style.color = 'red'
        document.querySelector('.imposters__voting').innerText = 'Voting has ended'
    }
    timerCount.innerText = counter

}, 1000)`

I tried counter = 0 but it didnt work

CodePudding user response:

else if(counter = 0) will never be executed, because else if(counter <= 10) is true for all values lower than 10.

Your if statements should look like this:

if(counter == 0) {}
else if(counter > 10) {}
else if(counter <= 10) {}

Also make sure to clear the interval in the first if statement: clearInterval(interval).

CodePudding user response:

Firstly, the order of your if statements is wrong. For example, when using counter <= 11 before counter <= 1, the first statement will always be true for values lower than 11 and the second statement will not be reached.

Secondly, you should use counter == 0 instead. This will check if the value is 0 and not set it to 0.

Lastly, it's recommended to stop your interval using clearInterval().

const timer = document.querySelector('.imposters__voting');
const timerCount = document.querySelector('.imposters__voting span');
let counter = 19;
let interval = setInterval(function() {
    timerCount.innerText = counter;
    if (counter > 10) {
        counter--;
    } else if (counter <= 0) {
        timer.innerText = 'Voting has ended';
        clearInterval(interval);
    } else if (counter <= 10) {
        counter--;
        timer.style.color = 'red';
    }
}, 1000);
<div >
  <span>20</span>
</div>

CodePudding user response:

You should use the clearInterval() method when you want to stop the interval code from running again. To do so, you need to capture the ID of that interval in a variable:

let intervalId = setInterval(function(){})

when you want to stop it from running again

clearInterval(intervalId)
  • Related