Search code examples
javascripttimercountdowncountdowntimer

Javascript countdown out of sync on different devices


Hi I am developing a count down for a product launch site so its important to get the synchronisation accurate. When running this on my netlify site on my laptop it works and when compared to countdowns online it is for the most part accurate. However when I open the page on my phone the time is completely out of sync. The entire countdown javascript is below. Can someone think of a fix?


//countdown
const countdown = document.querySelector('.countdown');

// Set Launch Date (ms)
const launchDate = new Date('June 30, 2020 00:00:00').getTime();

// Update every second
const intvl = setInterval(() => {
  // Get todays date and time (ms)
  const now = new Date().getTime();

  // Distance from now and the launch date (ms)
  const distance = launchDate - now;

  // Time calculation
  const days = Math.floor(distance / (1000 * 60 * 60 * 24));
  const hours = Math.floor(
    (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );
  const mins = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display result
  countdown.innerHTML = `
     <div>${days}<span>Days</span></div> 
     <div>${hours}<span>Hours</span></div>
     <div>${mins}<span>Minutes</span></div>
     <div>${seconds}<span>Seconds</span></div>
  `;

  // If launch date is reached
  if (distance < 0) {
    // Stop countdown
    clearInterval(intvl);
    // Style and output text
    countdown.style.color = '#17a2b8';
    countdown.innerHTML = 'Launched!';
    let modal = document.querySelector('.modalDialog');
    modal.classList.add('HideModalClass');
  }
}, 1000);


Solution

  • new Date().getTime(); will get the time on the machine it’s running on — if it’s running in the browser, this will be the user’s computer local time.