time/static/time.js
2020-07-12 19:41:02 +02:00

76 lines
2.4 KiB
JavaScript

(function () {
var _MONTHS_ = ['január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december'];
var _DAYS_ = ['vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat'];
var syncTimeout;
var clockTimeout;
var correct = 0;
function getSyncedDateTime() {
return new Date(new Date().getTime() - correct);
}
function fillZero(param) {
return param < 10 ? '0' + String(param) : String(param);
}
function sync() {
clearTimeout(syncTimeout);
var started;
var latency;
var syncRequest = new XMLHttpRequest();
syncRequest.onreadystatechange = function () {
switch (syncRequest.readyState) {
case XMLHttpRequest.OPENED:
started = new Date().getTime();
break;
case XMLHttpRequest.HEADERS_RECEIVED:
latency = (new Date().getTime() - started) / 2;
break;
case XMLHttpRequest.DONE:
correct = new Date().getTime() - (parseInt(syncRequest.responseText) + latency);
syncTimeout = setTimeout(sync, 10000);
break;
}
}
syncRequest.open('GET', 'getTime.php', true);
syncRequest.send();
}
function clock() {
var dateTime = getSyncedDateTime();
document.getElementById('year').innerHTML = dateTime.getFullYear();
document.getElementById('month').innerHTML = _MONTHS_[dateTime.getMonth()];
document.getElementById('date').innerHTML = dateTime.getDate();
document.getElementById('day').innerHTML = _DAYS_[dateTime.getDay()];
document.getElementById('time').innerHTML = fillZero(dateTime.getHours()) + ':' + fillZero(dateTime.getMinutes()) + ':' + fillZero(dateTime.getSeconds());
if (Math.abs(correct) < 100) {
document.getElementById('correct').style.display = 'none';
} else {
document.getElementById('correct').style.display = 'block';
document.getElementById('correct_seconds').innerHTML = (correct > 0 ? '+' : '') + (correct / 1000).toFixed(1);
}
clockTimeout = setTimeout(clock, 100);
}
document.getElementsByTagName('main')[0].ondblclick = function () {
sync();
}
clock();
sync();
})();