How to handle setInterval in Nuxt

I have a timer in my component, which is running with setInterval that starts in mounted() component.

Suppose this component is at http://localhost:3000/some-route.
Now how do I do clearInterval() whenever I go to another route like http://localhost:3000/ as I want to stop the timer.
I’ve used unmounted() but when you go to different route, the component doesn’t unmounts but if I go to same route (/some-route), setInterval runs again as the component is mounted again.

So, how do I clear the interval every time I go to different route?

Answer

I had to do it once, it’s a bit tricky because of the scope and the way it interacts with this (arrow functions basically). At the end, I also needed it to be available globally so I used it in pair with Vuex but you can totally use it in a component with some upper scope for the variable.

Here is a sample of code I’ve used

actionSetPolling({ state, dispatch }) {
  try {
    const myPolling = setInterval(async function () {
      if (someVariable !== 'COMPLETED') {
        // do stuff
      } else if (conditionToStop) {
        // this is facultative, but can be done here so far too
        window.clearInterval(myPolling)
      }
    }, 2000)
    dispatch('setPollingId', myPolling)
  } catch (error) {
    console.warn('error during polling', error.response)
    window.clearInterval(state.pollingId)
  }
}

setPollingId is an action that set’s a pollingId mutation, that way I can track it all along globally.

You could use the same while unmounting your component with this

beforeDestroy() {
  window.clearInterval(state.pollingId)
},

Not sure if it’s the best way of doing things but setInterval is by it’s nature, clunky and hacky out of the box IMO, especially in an SPA.