Clock that goes down too fast

Asked

Viewed 33 times

0

I’m trying to make a counter work when I click a button, it turns out that when a button is clicked more than once the counter starts to decrement too fast.

Source code:

var pomodoro = document.querySelector('#btn1');


    var count = new Number();
    
    function start () {
        if((count -1) >= 0) {
            count = count - 1;
            sessao.innerText = count;
            setTimeout('start()', 1000);
        }
    }
    
    pomodoro.onclick = function () {
        count = 1500;
        return start();
    }

Here’s a 30-second video link showing how the code is working.

  • So you want it to be called once and it can stop ? (because it happens such behavior quoted: the code is being called several times and then it ends up having the increment several times and your impression is that this is happening too fast). What is the expected behavior for your code

  • Whoa, Virgilio, good morning. My intention is that, when clicking again, it restarts the contagion normally, without decreasing too fast, as is happening there.

1 answer

2


Then use setInterval which can stop and then restart with clearInterval, that is, one creates the timer and the other to, example:

const pomodoro = document.querySelector('#btn1');
const source = document.getElementById("source");
let count = new Number();
let stopEvent = null;

function start () {
    if((count -1) >= 0) {
        count = count - 1; 
        source.innerHTML = count;
    }
    else 
    {
      if (stopEvent) {
        clearInterval(stopEvent);
      }
    }
}

pomodoro.onclick = function () {
    count = 1501;
    if (stopEvent) {
      clearInterval(stopEvent);
    }
    stopEvent = setInterval('start()', 1000);    
}
<p id="source"></p>
<button id="btn1">Iniciar</button>

It has been implemented very simple for your understanding, it can refactor some things, but the main intention is to understand that with setInterval can stop and restart when you want, the other way keeps calling in a bad process has no way to stop until the function is no longer invoked.

  • It worked, thanks, man.

  • @Maggrilmur if useful vote accepted as answer to your question

Browser other questions tagged

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