Display server time on client in Meteor


Question

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.

1
11
11/13/2014 9:57:53 PM

Accepted Answer

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>
21
1/9/2013 1:47:37 AM

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:

  • A more accurate computation of the server/client offset using NTP-style math, as opposed to just diffing the client and server time and ignoring round trip time.
  • The ability to use the server timestamps reactively to display values that will update themselves in templates and reactive computations.

Feel free to open pull requests on this, especially if you have ideas for better/more efficient ways to compute and maintain the offset.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon