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()
. Below code will help you to understand well.
<template name="Home">
<h4>{{timeremaining}}</h4>
</template>
Template.Home.helpers({
timeremaining : function(){
return Session.get('timeremaining');
}
});
Template.Home.onRendered(function () {
// time functions begin
var end_date = new Date(1476337380000); // I am getting timestamp from the db.
var run_every_sec = setInterval(function () {
var current_date = new Date();
var remaining = end_date.getTime() - current_date.getTime();
var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs(remaining/oneDay));
console.log(remaining); // am getting this log in every template.
if (remaining > 0) {
//set remaining timeLeft
Session.set('timeremaining',diffDays + ' Days ' + (Math.abs(end_date.getHours()-current_date.getHours())).toString() + ' Hrs ' + (Math.abs(end_date.getMinutes()-current_date.getMinutes())).toString() + ' Min ' + (60 - end_date.getSeconds()-current_date.getSeconds()).toString() + ' Sec ')
} else {
clearInterval(run_every_sec);
}
}, 1000);
//time functions end
}.bind(this));
Template.Home.onDestroyed(function () {
clearInterval(run_every_sec); // Here I cant remove this time interval
});
We can declare run_every_sec
as global function. If so How to pass end_date
. I dont think its wise idea to declare end_date
inside the run_every_sec
because its coming from db.
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.
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