I have a session variable that I want to update with a fixed periodicity. Say, I want this variable to be increased by 1 every 60 seconds.
It seems to me that the best place for doing this is inside the helpers section of the relevant template. I first tried to do this using setInterval as described here, but that didn't work (the function just didn't seem to repeat).
I then tried what I thought would be a straightforward solution, but this also doesn't work. See below. The helper variable 'currentPosition' is supposed to return the current minute of the day (plus an offset). However, it only does this when the template is first called and when the session variable 'offset' is changed in a function that's defined in the 'events' section, which responds to a click on a particular div (a 'next' button).
currentPosition: function () {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var w = h * 60 + m;
Session.set("position", w + Session.get("offset"));
return Session.get("position");
},
I would think that the above helper would actively update the value for 'currentPosition' every minute. Yet it does not.
So, my question is, how can I have a session variable change every, say, 60 seconds, increasing it by, say, 1, while the new value of the session variable is reflected within the app, when the variable is adjusted.
(If there's a straightforward and completely different solution which works in meteor, I'm not aware of it, so do point it out to me if I'm missing something obvious.)
Although you are using a reactive variable, it only gets set once - when the helper is first called. Therefore it doesn't run again. You need a function outside of the helper to set variable for you. Remember one important rule - helpers should never have side effects.
Here's a complete working example of how to create a timer:
<body>
{{> timer}}
</body>
<template name="timer">
<p>Total Seconds: {{seconds}}</p>
</template>
Template.timer.helpers({
seconds: function() {
return Template.instance().seconds.get();
}
});
Template.timer.created = function() {
var self = this;
this.seconds = new ReactiveVar(0);
this.handle = Meteor.setInterval((function() {
self.seconds.set(self.seconds.get() + 1);
}), 1000);
};
Template.timer.destroyed = function() {
Meteor.clearInterval(this.handle);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With