Last active
December 21, 2024 11:43
-
-
Save ethaizone/6abb1d437dbe406fbed6 to your computer and use it in GitHub Desktop.
Sync server time to client browser with JS. Implement follow Network Time Protocol.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original from http://stackoverflow.com/questions/1638337/the-best-way-to-synchronize-client-side-javascript-clock-with-server-date | |
// Improved by community and @jskowron | |
// Synchronize client-side clock with server time using an approximation of NTP | |
let serverTimeOffset = null; | |
function getServerTime(callback) { | |
if (serverTimeOffset === null) { | |
const scripts = document.getElementsByTagName("script"); | |
const currentScriptURL = scripts[scripts.length - 1].src; | |
const clientTimestamp = Date.now(); // Client timestamp before request | |
const xhr = new XMLHttpRequest(); | |
xhr.open("HEAD", `${currentScriptURL}?noCache=${clientTimestamp}`, true); | |
xhr.onload = function () { | |
if (xhr.readyState === 4 && xhr.status === 200) { | |
const serverDateHeader = xhr.getResponseHeader("Date"); | |
if (serverDateHeader) { | |
const serverTimestamp = Date.parse(serverDateHeader); | |
const nowTimeStamp = Date.now(); // Timestamp after response | |
// Calculate offset | |
serverTimeOffset = serverTimestamp - ((clientTimestamp + nowTimeStamp) / 2); | |
// Return synchronized time | |
const syncedDate = new Date(Date.now() + serverTimeOffset); | |
if (callback) callback(syncedDate); | |
} else { | |
console.error("Server did not return a valid Date header."); | |
} | |
} else { | |
console.error("Failed to fetch server time:", xhr.statusText); | |
} | |
}; | |
xhr.onerror = function () { | |
console.error("Network error while fetching server time."); | |
}; | |
xhr.send(null); | |
} else { | |
// Return cached offset-adjusted time | |
const syncedDate = new Date(Date.now() + serverTimeOffset); | |
if (callback) callback(syncedDate); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jskowron Thank you for be patient with me. Actually at that time I'm very busy until point that my brain isn't working properly.
Today I read your message carefully again and I agreed with you so I improved code.
Hope that next year will be happy years for everyone and thank you for who helped to contribute in this little code snippet.