Javascript 倒计时在不同设备上不同步
Javascript countdown out of sync on different devices
您好,我正在为产品发布网站开发倒计时功能,因此确保同步准确非常重要。当 运行 在我的笔记本电脑上的 netlify 网站上显示它时,它可以正常工作,并且与在线倒计时相比,它在很大程度上是准确的。但是,当我在 phone 上打开页面时,时间完全不同步。整个倒计时 javascript 如下。 有人能想出解决办法吗?
//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);
new Date().getTime();
将获取 运行 机器上的时间 — 如果浏览器中 运行,这将是用户计算机的本地时间。
您好,我正在为产品发布网站开发倒计时功能,因此确保同步准确非常重要。当 运行 在我的笔记本电脑上的 netlify 网站上显示它时,它可以正常工作,并且与在线倒计时相比,它在很大程度上是准确的。但是,当我在 phone 上打开页面时,时间完全不同步。整个倒计时 javascript 如下。 有人能想出解决办法吗?
//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);
new Date().getTime();
将获取 运行 机器上的时间 — 如果浏览器中 运行,这将是用户计算机的本地时间。