Meteor live clock (CLOSED)

Hello,
I’m trying to create a clock that updates in real-time.
So far I only had a clock that only update upon a refresh, however I started to rewrite it using ReactiveVars, without success.
can anyone help me?

UPDATE: GOT IT WORKING!

My html

        <div id="container">
    <div id="info">
      <div id="time">
        <span id="hours">{{clock_hour}}</span>:<span id="minutes">{{clock_minute}}</span>:<span id="seconds">{{clock_second}}</span>
      </div>
    </div>
  </div>
  </li>

My helper

clock_hour: function(){
 return Session.get('hour');
},
clock_minute: function(){
 return Session.get('minute');
},
clock_second: function(){
  return Session.get('second');
},


Reactive var (should update every second)

function getSecond(){
var d = new Date();
return d.getSeconds();
};

function getMinute(){
var d = new Date();
return d.getMinutes();
};
function getHour(){
var d = new Date();
return d.getHours();
};


Meteor.setInterval(function() {
    Session.set('second', getSecond());
    Session.set('minute', getMinute());
    Session.set('hour', getHour());
}, 1000);

That code can break. By getting each component of the time from separate calls to Date you can run into situations when the time changes on an hour/minute/second boundary and you will get the wrong time being reported.

1 Like

Here I call new Date() once

Meteor.setInterval(function() {
  var d = new Date();
    Session.set('second', d.getSeconds());
    Session.set('minute', d.getMinutes());
    Session.set('hour', d.getHours());
    Session.set('color', getHex(d));

}, 1000);

function pad(d) {
    return (d < 10) ? '0' + d.toString() : d.toString();
};

Template.triphtml.helpers({

clock_hour: function(){
 return pad(Session.get('hour'));
},
clock_minute: function(){
 return pad(Session.get('minute'));
},
clock_second: function(){
  return pad(Session.get('second'));
},

bg_color: function(){
  return Session.get('color');
},

I went for simplicity on this one

const curTime = new ReactiveVar(new Date());

Meteor.startup(() => {
    Meteor.setInterval(() => {
        curTime.set(new Date());
    }, 1000);
});

Template.clock.helpers({
    date() {
        return moment(curTime.get()).format("HH:mm:ss");
    }
});
4 Likes

That’s basically what I was drafting, too!