From bbacb12cf514480d7a34b3c39fdebc7ffb5a7315 Mon Sep 17 00:00:00 2001 From: Marius Gavrilescu Date: Sat, 18 Apr 2015 00:09:33 +0300 Subject: [PATCH] Use server time in 90-timers.js for more accurate timers --- js/90-timers.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/js/90-timers.js b/js/90-timers.js index d439299..e03ae08 100644 --- a/js/90-timers.js +++ b/js/90-timers.js @@ -1,8 +1,10 @@ +let offset = 0; + function update_timer(timer){ var start = parseInt(timer.dataset.start); var stop = parseInt(timer.dataset.stop); var value = parseInt(timer.dataset.value); - var now = Math.floor(Date.now() / 1000); + var now = Math.floor(Date.now() / 1000) + offset; var left = stop - now; var total = stop - start; @@ -23,7 +25,17 @@ function update_timer(timer){ } } -$(() => $('.timer').each(item => { - update_timer(item); - setInterval(() => update_timer(item), 1000); -})); +$(() => { + $('.timer').each(item => { + update_timer(item); + setInterval(() => update_timer(item), 1000); + }); + let xhr = new XMLHttpRequest(); + xhr.open('HEAD', '/'); + xhr.onload = () => { + let srvtime = Date.parse(xhr.getResponseHeader('Date')); + offset = Math.ceil((srvtime - Date.now()) / 1000); + console.log("Offset from server: " + offset); + }; + xhr.send(); +}); -- 2.39.2