Countdown js

0

I have a code that counts down from 20 to 0. At this point the user has to do certain tasks and when he completes, he presses a button. At the time he presses the button, the counter must stop in the exact second it was pressed. Here are 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 the case is at the exact moment it is clicked and this is important):

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

But this if does not work and I can not think of anything else.

    
asked by anonymous 20.10.2018 / 15:12

2 answers

0

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

See 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>
    
20.10.2018 / 16:03
-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:)

    
20.10.2018 / 15:44