Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Clear interval when switching between Vuejs Routes

I'm facing a problem where an Interval from a Vue component keeps running when I navigate to another route of my app.

I'm using Vue router, having the next configuration:

const routes = [
{
    path: '/',
    name: 'Home',
    component: Home
},
{
    path: '/login',
    name: 'Login',
    component: LoginMenu
},
{
    path: '/canvas',
    name: 'Canvas',
    component: AllElement
},
{
    path: '/querybuilder',
    name: 'QueryBuilder',
    component: QueryBuilder
},
{
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard
}

]

The interval is in the AllElement component. As I'm using Vue router, AllElement is loaded into the router-view, and when I switch to Home.vue component, it will be loaded into the router-view but the AllElement's interval will keep running.

Here's where the interval is being initiated

mounted() {
    this.fetchLastBucketData();
    setInterval(() => {
        this.fetchLastBucketData();
    }, 3000);
}

Any solutions?

almost 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Assign the setInterval to a data property and clear when the component is unmounted :

data(){
   return{
      interval:null;
  };
},
mounted() {
    this.fetchLastBucketData();
  this.interval =  setInterval(() => {
        this.fetchLastBucketData();
    }, 3000);
},
unmounted(){ // destroyed  in Vue 2
   clearInterval(this.interval)
}



in Composition API :

import {ref,onMounted,onUnmounted} from 'vue'
....
const interval =ref(null)

onMounted()=> {
   fetchLastBucketData();
    interval.value =  setInterval(() => {
        fetchLastBucketData();
    }, 3000);
})

onUnmounted(()=>{ 
   clearInterval(interval.value)
 }
)


almost 4 years ago · Santiago Trujillo Report

0

I am assuming you are using Vue-3.

You need to add the code to clear the interval. Since you want the interval to stop on route change, so it should be placed in unmounted hook (destroyed in Vue-2). Something like this:

mounted() {
    this.fetchLastBucketData();
    this.canvasInterval = setInterval(() => {
        this.fetchLastBucketData();
    }, 3000);
}

unmounted() {
    clearInterval(this.canvasInterval); // - Clears Interval
}
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!