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

157
Visualizações
JavaScript countdown timer that still runs when the user exits the page

For my game, I need a countdown timer (hours:minutes) that still runs when the user closes the web page, preferably in vanilla JavaScript.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For this you could store the time that the user started the countdown as a Date object and then calculate the difference every second to update the countdown. However, you need to store this value in localstorage so it is not erased when the webpage is closed.

METHOD

Here is the full method, obviously you will need to check when the timer reaches zero and implement what you want to happen, but the timer works for now.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <p id="timer"></p>
    <button onclick="startTimer()">start</button>
    <script>
      time = parseInt(localStorage.getItem("timer"));

      if (time != null) {
        let timerInterval = setInterval(timer, 100);
      }

      function timer() {
        time = parseInt(localStorage.getItem("timer"));
        console.log();
        let now = new Date();
        let countDownTime = new Date(time);
        timerInMs = countDownTime.getTime() - now.getTime();
        document.querySelector("#timer").innerHTML = msToTime(timerInMs);
      }

      function msToTime(duration) {
        console.log(duration);
        var seconds = Math.floor((duration / 1000) % 60),
          minutes = Math.floor((duration / (1000 * 60)) % 60),
          hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        return (
          hours + " hours - " + minutes + " minutes - " + seconds + " seconds"
        );
      }

      function startTimer() {
        timeInMs = 1000000; // time to count down to in ms
        const now = new Date();
        const countDownTime = new Date(now.getTime() + timeInMs);
        localStorage.setItem("timer", countDownTime.getTime()); // Store in local storage
        let timerInterval = setInterval(timer, 500);
      }
    </script>
  </body>
</html>

msToTime function

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