0

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

embers02
  • 23
  • 4

1 Answers1

1

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

oflint_
  • 297
  • 1
  • 8
  • Im a bit confused on how I would do this – embers02 Feb 02 '22 at 22:16
  • I have just added a basic method to the answer :) – oflint_ Feb 02 '22 at 22:22
  • thank you but when I put it in a function and window.onload it, it just returns a number like this: 1643840952233, and only updates when you refresh the page, even if I put it in a setinterval. Im not very good at javascript so I probably just did it wrong – embers02 Feb 02 '22 at 22:32
  • Here is what I did with it by the way https://pastebin.com/ykMCEZ7Z – embers02 Feb 02 '22 at 22:33
  • This is just the basic idea. You would also need another function to update the display every few hundred ms. You also need to convert ms to hours and minutes. This function can be found here: https://stackoverflow.com/a/19700358/12682491 – oflint_ Feb 02 '22 at 22:35
  • I got it to work, but it counts up instead of down: https://pastebin.com/Bkd102aX – embers02 Feb 02 '22 at 22:46
  • You only want to set the initial values once, and then have another function to calculate the difference. In your code, at every interval you change the countDownTime, which should not be changed. – oflint_ Feb 02 '22 at 22:51
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241668/discussion-between-embers02-and-oflint). – embers02 Feb 02 '22 at 23:03
  • I've just updated my answer with a full working solution, hope this helps :) – oflint_ Feb 03 '22 at 16:55