Skip to content
Advertisement

How to synchronise a timer for everyone client

I have a working timer, but it runs from 25 seg every time who the website is visited by a client, I want to synchronise it. F.E. if i visit my webpage in mY Pc, and when it show 15seg left, i visit it from other pc and i want it to show 15 left too.

function timerr(){
    var initial = 25000;
    var count = initial;
    var counter;
    var initialMillis;

    function timer() {
        if (count <= 0) {
            clearInterval(counter); 
            return;
        }
        var current = Date.now();

        count = count - (current - initialMillis); 
        initialMillis = current;
        displayCount(count);

    function displayCount(count) {
        var res = count / 1000;
        if (res<0.1){
            document.getElementById("timer").innerHTML = "";
        }
        else{
            tiempo = res.toPrecision(count.toString().length);
            tiempo_corto = tiempo.slice(0,-1);
            document.getElementById("timer").innerHTML = tiempo_corto;
    }
    }
    clearInterval(counter);
    initialMillis = Date.now();
    counter = setInterval(timer, 10);
}

Advertisement

Answer

If you want everyone to have the same timer count down every 25 seconds and stop at the exact same time, then you can simply use timestamps to keep everything in sync. Here’s an example countdown timer that’ll restart every 6 seconds (from 5 to 0) and will hit zero at the exact same time for everyone (unless their computer clock is off).

const timerElement = document.getElementById('timer')
const TIMER_DURATION = 6

function step() {
  const timestamp = Date.now() / 1000
  const timeLeft = (TIMER_DURATION - 1) - Math.round(timestamp) % TIMER_DURATION
  timerElement.innerText = timeLeft
  
  const timeCorrection = Math.round(timestamp) - timestamp
  setTimeout(step, timeCorrection*1000 + 1000)
}
step()
<p id="timer"></p> seconds

Try it – open this page up in two different tabs and run it. This is set up to automatically account for the fact that setTimeout doesn’t always trigger at the delay you asked it to do so (it’ll adjust the next setTimeout with a timeCorrection value to correct these issues).

The basic principle is that we’re getting the current timestamp and modding it by the amount of time we want this timer to last (6 seconds in the above example). This value will always be the same for everyone, and will always be a number that ranges from 0 to 5. It will also be a number that counts up every second (which is why we then subtract (TIMER_DURATION - 1) from it, to cause the number to count down instead).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement