Issue with auto-updating time

Hi,

Following a beginner Meteor book I used this code in my client/client.js file


Meteor.setInterval(function() {
var currentDate = new Date();
Session.set('now',
currentDate.toLocaleTimeString()
);
}, 1000);

Template.timeDisplay.helpers({
currentTime: function() {
return Session.get('now');
}
});

Before I used this code, we had a non-updating version of the time which was displayed in the template/live page correctly.

The code above does not though. Anyone see the error?

a timeout only runs once, what you are looking for is an interval

Template.currentTime.onCreated(function(){
  var instance = this;
  instance.now = new ReactiveVar();
  instance.interval = Meteor.setInterval(function(){
    var now = new Date();
    instance.now.set( now.toLocaleTimeString() );
  }, 1000);
});
Template.currentTime.helpers({
  currentTime(){
    return Template.instance().now.get();
  }
});
Template.currentTime.onDestroyed(function(){
  var instance = this;
  if(instance.interval) Meteor.clearInterval(instance.interval);
});
2 Likes