1

I want to run setInterval just in the scope of a specific component (limit to that component not the whole of application) because I'm using SPA mode by Quasar framework.

When I set this function it causes run in everywhere even I changed the page's URL. Also, I checked this link (how to use setInterval in Vue component) but it wasn't my answer.

My sample code:

methods:
  testInterval: function () {
    setInterval(() => this.playCMD(), 2000)
  },
  playCMD: function () {
    // Do something
    console.log('Do something')
  }

Also, it's better to say I want to limit doing something in the specific scope in VueJs, not in the whole of the application when we use it through SPA mode.

Ali Hallaji
  • 3,712
  • 2
  • 29
  • 36
  • Can you elaborate. What does it mean "it causes run everywhere" ? – ajobi Mar 22 '20 at 10:05
  • @ajobi I want to stop the setInterval function when I change my page in SPA mode, in another word I want to finish setInterval when the process of that page is finished. – Ali Hallaji Mar 22 '20 at 10:53

2 Answers2

3

I haven't used the Quasar framework but you could try these options:

  1. Subscribing to the Vue lifecycle 'destroyed' event and then do a clearTimeout.

Or

  1. If you're using Vue-Router you can use In-Component Guards which are events when you navigate to another component, which you could use to do a clearTimeout.

     data: () => {
         return {
             timer: null
         };
     },
     methods: {
         testInterval() {
             this.timer = setInterval(this.playCMD, 2000)
         }
     },
     beforeRouteLeave (to, from, next) {
         if(this.timer)
             clearInterval(this.timer);
         next();
     }
    

EDIT: Thanks @Ali Hallaji. You have to add a call to the next function to proceed through the pipeline, as described here.

tony19
  • 125,647
  • 18
  • 229
  • 307
Shoejep
  • 4,414
  • 4
  • 22
  • 26
  • 1
    I would go with the first option -> lifecycle hooks. I have a suspicion that there would be a leak happening if you would destroy the component, but not necessarily change the route (for example with conditional rendering with v-if) – ajobi Mar 22 '20 at 13:28
  • Unfortunately, I can't find much documentation for your use case, only [this](https://quasar.dev/quasar-cli/developing-ssr/writing-universal-code#Component-Lifecycle-Hooks) incase you're using SSR. You could also try the 'beforeDestory' event instead of 'destroyed', or as a last resort you could pass the route to the function and then compare if it's equal to the current route. – Shoejep Mar 22 '20 at 19:01
0

@Shoejep thank you so much, It works. we had to add next() function into beforeRouteLeave. Please see below:

beforeRouteLeave (to, from, next) {
    if(this.timer)
        clearInterval(this.timer)
        next()
}

Because if we do not put the next() into that function we can't go to another routes.

Ali Hallaji
  • 3,712
  • 2
  • 29
  • 36