Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display server time on client in Meteor

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.

like image 765
Daniel Jonce Evans Avatar asked Jan 08 '13 23:01

Daniel Jonce Evans


2 Answers

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>
like image 178
TimDog Avatar answered Nov 15 '22 20:11

TimDog


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.

like image 29
Andrew Mao Avatar answered Nov 15 '22 21:11

Andrew Mao