Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
My JS timer clock is not stopping when clicked twice on start button

I have a simple HTML stopwatch logic where I can start and stop the clock with the button click. By clicking on the start button, one can start the timer (shows current time) and update every second. One can stop it by clicking stop button. But if one clicks on start button twice, there is nothing I can do to stop the timer. Below is my code:

var hour = document.getElementById("hoursOut");
  var minute = document.getElementById("minsOut");
  var second = document.getElementById("secsOut");
  var btnStart = document.getElementById("btnStart");
  var btnStop = document.getElementById("btnStop");

  var waitTimer;

  function displayTime() {
    var currentTime = new Date();
    var currentHour = currentTime.getHours();
    var currentMinute = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    hour.innerHTML = twoDigit(currentHour) + ":";
    minute.innerHTML = twoDigit(currentMinute) + ":";
    second.innerHTML = twoDigit(currentSeconds);
  }

  function twoDigit(digit) {
    if (digit < 10) {
      digit = "0" + digit;
    }
    return digit;
  }

function startClock() {
    waitTimer = setInterval(displayTime, 1000);
  }

  function stopClock() {
    clearInterval(waitTimer);
  }

  btnStart.onclick = startClock;
  btnStop.onclick = stopClock;
    <h1>JavaScript Clock</h1>

    <div id="calendarBox">
      <!-- OUTPUT TIME VALUES -->
      <p class="timeDisplay">
        <span id="hoursOut">00:</span>
        <span id="minsOut">00:</span>
        <span id="secsOut">00</span>
      </p>

      <!-- BUTTON SET -->
      <input id="btnStart" type="button" value="START" />
      <input id="btnStop" type="button" value="STOP" />
    </div>

I have checked some answers in stackoverflow but most solutions uses a for-loop from 0 to 1000 until it finds the interval id and stop all of them using loop. I am confident there should be an elegant solution than that.

// some stackoverflow suggested answer
    for (var i = 1; i < 99999; i++)
         window.clearInterval(i);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A possible solution is to prevent the problem before it happens. You can place a check on the running timer (Is there a way to check if a var is using setInterval()?).

In this case you could just have a global timer variable var timer = false the with add a check to the start function. Then the stop function will set the timer variable back to false.

     function startClock() {
        if(!timer){
          timer = true
          waitTimer = setInterval(displayTime, 1000);
        }
        else return
      }
    
      function stopClock() {
        clearInterval(waitTimer);
        timer = false
      }
about 4 years ago · Juan Pablo Isaza Relatório

0

when you double click you start a new setInterval(). So you now have two set intervals running. Only problem is you can't access the first one cause you named the second one the same name. Check if waitTimer exists and if it does stop it. see code:

UPDATE: actually you don't even need an if statement. just call stopClock() before you set waitTimer -- code snippet adjusted

var hour = document.getElementById("hoursOut");
  var minute = document.getElementById("minsOut");
  var second = document.getElementById("secsOut");
  var btnStart = document.getElementById("btnStart");
  var btnStop = document.getElementById("btnStop");

  var waitTimer;

  function displayTime() {
    var currentTime = new Date();
    var currentHour = currentTime.getHours();
    var currentMinute = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    hour.innerHTML = twoDigit(currentHour) + ":";
    minute.innerHTML = twoDigit(currentMinute) + ":";
    second.innerHTML = twoDigit(currentSeconds);
  }

  function twoDigit(digit) {
    if (digit < 10) {
      digit = "0" + digit;
    }
    return digit;
  }

function startClock() {
    stopClock();
    waitTimer = setInterval(displayTime, 1000);
  }

  function stopClock() {
    clearInterval(waitTimer);
  }

  btnStart.onclick = startClock;
  btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>

    <div id="calendarBox">
      <!-- OUTPUT TIME VALUES -->
      <p class="timeDisplay">
        <span id="hoursOut">00:</span>
        <span id="minsOut">00:</span>
        <span id="secsOut">00</span>
      </p>

      <!-- BUTTON SET -->
      <input id="btnStart" type="button" value="START" />
      <input id="btnStop" type="button" value="STOP" />
    </div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda