Meteor redraw clock every second

  Template.display_time.time = function() {
    var date = new Date();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var now = addZero(hour) + ":" + addZero(minute);
    return now
  };

At the moment im using this code to display the time. But I've been trying to use simple javascript to update it every second, yet it wont show up on the page. Is there a meteor friendly way to do this using the function above? Like using setTimeout on 1 second interval..

The javascript I used to use.

function updateTime() {
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    if (hours < 10)
    {
        hours = "0" + hours;
    }
    if (minutes < 10)
    {
        minutes = "0" + minutes;
    }
    var v = hours + ":" + minutes + " ";
    setTimeout("updateTime()",1000);
    document.getElementById('time').innerHTML=v;
}
updateTime();

Upvotes: 2

Views: 360

Answers (1)

Brad M
Brad M

Reputation: 7898

The reason that method doesn't work is because it isn't a reactive data source.

Try the following.

Template.display_time.time = function() {
    return Session.get('time');
};

Meteor.setInterval(function() {
    Session.set('time', getTime());
}, 1000);

See the documentation on Deps

"Meteor has a simple dependency tracking system which allows it to automatically rerun templates and other computations whenever Session variables, database queries, and other data sources change."

Upvotes: 5

Related Questions