How to periodically update a variable using a meteor

I have a session variable that I want to update at a fixed frequency. Let's say I want this variable to be incremented by 1 every 60 seconds.

It seems to me that the best place for this is inside the helpers section of the corresponding template. At first I tried to do this using setInterval, as described here , but it did not work (the function just did not repeat).

Then I tried what, in my opinion, would be a simple solution, but that won't work either. See below. The auxiliary variable 'currentPosition' should return the current minute of the day (plus the offset). However, this only happens when the template is called for the first time and when the "offset" variable of the session changes in the function defined in the "events" section, which responds to a click on a particular div ("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. But this is not so.

So my question is: how can I change the session variable every time, say, 60 seconds, increasing it by, say, 1, while the new value of the session variable is reflected inside the application when the variable is adjusted.

(If there is a direct and completely different solution that works in a meteor, I don’t know about it, so tell me if I miss something obvious.)

+6
source share
1 answer

Although you use a reactive variable, it is set only once - when the helper is first called. Therefore, it does not start again. To set a variable you need a function outside . Remember one important rule - helpers should never have side effects .

Here is a complete working example of creating a timer:

HTML

 <body> {{> timer}} </body> <template name="timer"> <p>Total Seconds: {{seconds}}</p> </template> 

Js

 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); }; 
+14
source

Source: https://habr.com/ru/post/979428/


All Articles