Reputation: 4392
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.
Upvotes: 1
Views: 2615
Reputation: 4839
I haven't used the Quasar framework but you could try these options:
Or
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.
Upvotes: 3
Reputation: 4392
@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.
Upvotes: 0