[Vuejs]-Why is beforeDestroyed function not working?

2👍

setInterval returns an interval, which is used to clear the interval, which means that you need to store the setInterval returned value into a variable, also define the variable in the data object so it will be accessible everywhere in the component.

this.interval = setInterval(this.clock, 1000);

Then, use this.interval to clear the interval in beforeDestroy.

clearInterval(this.interval);

1👍

The below answer won’t need you to have a beforeDestroy hook if all you are doing in it is to clear the interval.

mounted() {
  const interval = setInterval(this.clock, 1000);
    this.$once('hook:beforeDestroy', () => {
       clearInterval(interval);
    })

},

Leave a comment