Meteor : How To Clearinterval() Ondestroyed() Created In Onrendered()
I have a countdown function to run every sec, So i proffered setInterval(). After I moved to another template, the interval function keep on running. How to destroy it onDestroyed(
Solution 1:
If you store the interval in file scope like Repo suggested, you'll have problems if there's ever more than one instance of the template at a time: both instances will use the same run_every_sec
variable. In this case, you'll need to store the interval on the template instance, which can be accessed as this
inside onRendered
and onDestroyed
:
Template.Home.onRendered(function () {
this.run_every_sec = setInterval(/* ... */);
});
Template.Home.onDestroyed(function () {
clearInterval(this.run_every_sec);
});
That way, each instance of the template will have its own run_every_sec
property.
Solution 2:
You should declare "run_every_sec" outside "onRendered".
So instead of this:
Template.Home.onRendered(function () {
// time functions beginvar end_date = newDate(1476337380000); // I am getting timestamp from the db.var run_every_sec = setInterval(function () {
..do this:
var run_every_sec;
Template.Home.onRendered(function () {
// time functions beginvar end_date = newDate(1476337380000); // I am getting timestamp from the db.
run_every_sec = setInterval(function () {
then it will be available in "onDestroyed"
Solution 3:
You should use Meteor's setInterval and clearInterval to make sure they run within a fiber. You can find more info here https://docs.meteor.com/api/timers.html.
var intervalID
Template.myTemplate.onRendered(function() {
intervalID = Meteor.setInterval(function() {
//do something
}, 1000)
})
Template.myTemplate.onDestroyed(function() {
Meteor.clearInterval(intervalID)
})
Post a Comment for "Meteor : How To Clearinterval() Ondestroyed() Created In Onrendered()"