Countdown js

Asked

Viewed 538 times

0

I have a code that counts backwards from 20 to 0. At that time, the user has to do certain tasks and when completed, he presses a button. The minute he pushes the button, the counter has to stop at the exact second it was pressed. Follows the codes:

Javascript:

var count = new Number();
var count = 21;  
    function start(){
        if((count - 1) >= 0){
            count = count - 1;
            tempo.innerText=count;
            setTimeout('start();',1000);
            console.log("tempo:" + count);
        }
}

I tried to create the following if to stop as soon as the button is disabled (which in this case is the exact moment it is clicked and this is important):

if(document.getElementById("myBtn").disabled == true){
clearTimeout(count);
}

But that if doesn’t work and I can’t think of anything else.

2 answers

0


You need to create a variable to contain your timer, so that by clicking a button you can stop using clearInterval.

Take this example:

var count = new Number();
var count = 21;  
// variável para o contador
var contador;
var tempo = document.getElementById("tempo");

function start(){
  if((count - 1) >= 0){
    count = count - 1;
    
    tempo.innerText=count;
    contador = setTimeout(start,1000);
    console.log("tempo:" + count);
  }
}

function stop() {
  tempo.innerText = "Parado em " + count;
  clearInterval(contador);
}

// adiciona um evento para parar ao clicar no botão
document.getElementById("parar").addEventListener("click", stop, false); 

start();
<p>
   <span id="tempo"></span>
</p>
<p>
  <button id="parar">
    Parar contador
  </button>
</p>

-1

You can do the following

var timer = {count: 20};
var start = setInterval(function (timer) {
  if  (timer.count == 0) {
    clearInterval(start);
  }
  console.log(timer.count);
  timer.count--;
}, 1000, timer);

Just to give you a light :)

  • 1

    it wasn’t me who gave the -1, I think who gave it was because there’s the stop button count!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.