0

I want to create a 3 hours countdown that runs in the background and repeats when it reaches 00:00:00. How can I do it using HTML and javascript? Thank you!

zultz
  • 224
  • 2
  • 9
  • 2
    Does this answer your question? [How to write a countdown timer in JavaScript?](https://stackoverflow.com/questions/20618355/how-to-write-a-countdown-timer-in-javascript) – Andy Ray May 24 '21 at 02:48
  • 1
    Thanks for your reply but I want the countdown to continuously run even the user leaves the page – zultz May 24 '21 at 02:57
  • 1
    Stackoverflow isn't a code writing service. Please read [how to ask](https://stackoverflow.com/help/how-to-ask). – Andy Ray May 24 '21 at 02:59

2 Answers2

0

You can use Web Worker:

// index.html

<div id="box">60</div>
<script>
    let box = document.getElementById('box');
    let worker = new Worker('countdown.js');
    worker.postMessage(60);
    worker.onmessage = function (event) {
        box.innerHTML = event.data;
    }
</script>
// countdown.js

onmessage = function (e) {
    let num = e.data;
    let count = setInterval(function () {
        postMessage(--num);
        if (num <= 0) {
            clearInterval(count);
            close();
        }
    }, 1000);
}
Royal Ys
  • 1
  • 2
-1

For background countdown. I think the big issue that you need to face is when you are leave the page or open a new tabs. right? Do you want to make the countdown work even the tab is not active?

maybe requestAnimationFrame is helpful for you.

function showTime() {
  remainingTime = getRemainingTime(endTime);
  var seconds = pad((remainingTime / 1000));
  console.log('remain time is: ', seconds + " sec")

  if (remainingTime >= 1000) {
    window.requestAnimationFrame(showTime);
  } else {
    console.log('Time up!!!')
  }
}

function getRemainingTime(deadline) {
  var currentTime = new Date().getTime();
  return deadline - currentTime;
}

function pad(value) {
  var sl = (""+Math.floor(value)).length;
  if(sl > 2){
    return ('0' + Math.floor(value)).slice(-sl);
  }
  return ('0' + Math.floor(value)).slice(-2);
}


endTime = new Date().getTime() + 1000*60;
window.requestAnimationFrame(showTime);

Demo here: https://codepen.io/quanhv/pen/oNZWxvB

Dharman
  • 30,962
  • 25
  • 85
  • 135
Quân Hoàng
  • 371
  • 3
  • 9