Using Meteor, what would be an efficient way to keep a running clock (h:m:s) on the client that displays the server's time?
The JavaScript/PHP answers I've found typically involve getting the server time periodically and calculating the difference between that and the client.
What would that look like with Meteor?
UPDATE: A lot has changed since I originally posted this question. If you're interested in a pre-built solution, I recommend taking a look at Meteor Timesync by @mizzao. Install it by running meteor add mizzao:timesync
in your console.
David Greenspan gets the client time in this presentation on Spark around 14:30. I've modified this code slightly to get server side time:
Javascript:
if (Meteor.isClient) {
Meteor.startup(function () {
setInterval(function () {
Meteor.call("getServerTime", function (error, result) {
Session.set("time", result);
});
}, 1000);
});
Template.main.time = function () {
return Session.get("time");
};
}
if (Meteor.isServer) {
Meteor.methods({
getServerTime: function () {
var _time = (new Date).toTimeString();
console.log(_time);
return _time;
}
});
}
And the HTML:
<body>
{{> main}}
</body>
<template name="main">
{{time}}
</template>
There is very good information on this thread. I've pulled everything together into a smart package for Meteor:
https://github.com/mizzao/meteor-timesync
There are two main things I added beyond what is already here:
Feel free to open pull requests on this, especially if you have ideas for better/more efficient ways to compute and maintain the offset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With