Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(). 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.

like image 923
Ramesh Murugesan Avatar asked Dec 20 '22 01:12

Ramesh Murugesan


1 Answers

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.

like image 84
user3374348 Avatar answered Dec 24 '22 00:12

user3374348