Разниться время в таймере (между php и js)
Столкнулся с проблемой, что на стороне клиента таймер на несколько секунд впереди, в сравнении с с сервером.
При обновлении страницы сперва интервал выводиться со стороны сервера, а после инициализации js таймер начинает срабатывать и отсчитывает время, но на несколько секунд быстрее нежели со стороны сервера.
Ниже привожу часть кода с бэка и фронта.
бэк php:
$now = new DateTime('now');
$midnight = new DateTime('tomorrow 00:00');
$interval = $now->diff($midnight);
$this->assign('interval', $interval->format('<span>%H:%I:%S</span>'));
$this->assign('eventTime', $midnight->format('U'));
$this->assign('currentTime', $now->format('U'));
фронт html:
<button type="button" class="btn btn-danger btn-lg timer-numbers" id="bonus-left">{{ (user.next_bonus >= eventTime ? 'Осталось ' ~ interval : 'Получить бонус')|raw }}</button>
<div id="countdown" class="timer-line"><span></span></div>
фронт js:
let currentTime = +'{{ currentTime * 1000 }}';
eventTime = +'{{ eventTime * 1000 }}';
class Countdown {
constructor(timer, countdown, from, to) {
this.timer = timer;
this.countdown = countdown;
this.start = from;
this.finish = to;
this.run();
}
run() {
let distance = this.finish - this.start,
days, hours, minutes, seconds,
percent;
let countdown = setInterval(_ => {
let point = new Date().getTime() - this.start,
localDistance = this.finish - new Date().getTime();
days = Math.max(0, Math.floor(localDistance / (1000 * 60 * 60 * 24)));
hours = Math.max(0, Math.floor((localDistance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
minutes = Math.max(0, Math.floor((localDistance % (1000 * 60 * 60)) / (1000 * 60)));
seconds = Math.max(0, Math.floor((localDistance % (1000 * 60)) / 1000));
percent = point * 100 / distance;
if (hours == 0 && minutes == 0 && seconds == 0 || percent >= 100) clearInterval(countdown);
if (hours == 0 && minutes == 0 && seconds == 0) {
takeBonus(countdown); // exit
return false;
}
this.countdown.children[0].innerText =
(hours < 10 ? '0' + hours : hours) + ':' +
(minutes < 10 ? '0' + minutes : minutes) + ':' +
(seconds < 10 ? '0' + seconds : seconds);
this.timer.querySelector('.timer-line > span').style.width = `${percent}%`;
}, 1000);
}
}
window.onload = _ => {
new Countdown(
document.getElementById('countdown'),
document.getElementById('countdown').previousElementSibling,
currentTime,
eventTime
);
};
Если есть вопросы по коду, пишите! Заранее благодарю за помощь.