Skip to content

Instantly share code, notes, and snippets.

@ahume
Created November 19, 2011 01:10
Show Gist options
  • Save ahume/1378254 to your computer and use it in GitHub Desktop.
Save ahume/1378254 to your computer and use it in GitHub Desktop.
Simple example clock based on the time sent from the sever.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Clock based on server time</title>
</head>
<body>
<h1>Clock demo for Kylie</h1>
<p><span id="hour"></span>:<span id="minute"></span>:<span id="second"></span></p>
<script>
(function() {
// Get some DOM nodes to put content in.
var hour = document.getElementById("hour"),
minute = document.getElementById("minute"),
second = document.getElementById("second");
// Calculate the offset in milliseconds between server and client
// I've used an ISO 8601 formatted string, which the server should be able to create,
// but you could pass in any arguments acceptable to the Date() object.
var offset = new Date("2011-11-19T18:24:12.053Z") - Date.now();
// Every second calculate the new time.
window.setInterval(function() {
// Get the current time in milliseconds and allow for the server offset;
var m = Date.now() + offset;
// Create a new date object and write the time into the page.
var date = new Date(m);
hour.innerHTML = date.getHours();
minute.innerHTML = date.getMinutes();
second.innerHTML = date.getSeconds();
}, 1000);
})();
</script>
</body>
</html>
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment