embers02
embers02

Reputation: 23

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.

Upvotes: 0

Views: 413

Answers (1)

oflint_
oflint_

Reputation: 297

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

Upvotes: 1

Related Questions