veliovgroup / flow-router

🚦 Carefully extended flow-router for Meteor
https://packosphere.com/ostrio/flow-router-extra
BSD 3-Clause "New" or "Revised" License
201 stars 30 forks source link

Clearing a timer/interval when leaving a path #79

Closed meecect closed 4 years ago

meecect commented 4 years ago

I realize it isn't the most meteor-like way of doing this, but on a particular route I have a setinterval call that periodically runs some transitions on the page. I noticed today that after I leave that route, the interval continues to run. I guess I can use a triggersExit, and I see that the context is available, but do I have access to the template instance? I store a reference to the timer in the instance. Would I have to instead store the timer variable on the window object?

Are there other more clever ways to do this? Basically I have several calendar displays and I swap them out and increment their months periodically, and they continuously rotate through the year (its a kiosk with calendars on it for workplace schedules)

When I navigate away from the kiosks display, they continue to rotate in the background (i see console messages indicating the setinterval continues to run).

meteor 1.10.2 flow-router 3.75 chrome mac

dr-dimitru commented 4 years ago

Hello @meecect ,

Thank you for detailed description. Would you post actual route definition? A lot of depends from how you render a template

meecect commented 4 years ago

basically this:

const scrollToTop = () => {
  setTimeout(() => {
    if (!window.location.hash) {
      window.scroll(0, 0);
    }
  }, 25);
};

FlowRouter.triggers.enter([scrollToTop]);

const trackRouteClose = (context) => {
  console.log("move-from-home", context);
  clearInterval(window.timer);

};

// Set up all routes in the app
FlowRouter.route('/', {
  name: 'App.home',
  action() {
    BlazeLayout.render('App_body', { main: 'App_home' });
  },
  triggersExit: [trackRouteClose]
});

This works, I was just wondering if I can avoid making a reference to the timer on the window object, or if there is anything in blaze that lets a template know when it is being 'unviewed'

tanutapi commented 4 years ago

What about clear your timer in template.onDestroyed?

Template.App_home.onRendered(function() {
  this.timer = setInterval(() => {
    if (!window.location.hash) {
      window.scroll(0, 0);
    }
  }, 1000);
});

Template.App_home.onDestroyed(function() {
  clearInterval(this.timer);
});
meecect commented 4 years ago

huh, I didn't even know that was available. It should work, so I'll give that a try. Thanks so much.

dr-dimitru commented 4 years ago

@tanutapi great suggestion, I was thinking about the same .onDestroyed method @meecect I'm glad this was quickly solved.

Please support this project with: