Skip to content

Instantly share code, notes, and snippets.

@sustained
Last active July 16, 2022 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sustained/1ea5ed762aeb88b6f42cd6300e49872d to your computer and use it in GitHub Desktop.
Save sustained/1ea5ed762aeb88b6f42cd6300e49872d to your computer and use it in GitHub Desktop.
Automatically clean up timers (setInterval, setTimeout) and event listeners (addEventListener) for Vue.js.

What?

It automatically cleans up timers and event listeners in beforeUnmount.

Why?

Because who wants to write boilerplate? And I was bored. And it seemed like a really good idea, until I wrote it.

Note

I didn't actually test this. But... maybe it works, right?

Installation

import Vue from "vue";
import VueCleanup from "@/plugins/VueCleanup.js";

Vue.use(VueCleanup);

Usage

// Somecomponent.vue
export default {
  created() {
    this.$setInterval(this.doInterval, 2000);
    this.$addEventListener("resize", this.onResize, { passive: true });
  },
  methods: {
    doInterval() {
      console.log("Are we there yet?");
    },
    onResize() {
      console.log("Hey stop triggering so much layout/reflow. :(");
    }
  }
}
let VueCleanUp = {
install(Vue, options) {
Vue.prototype.$_timeouts = [];
Vue.prototype.$_intervals = [];
Vue.prototype.$_listeners = [];
Vue.mixin({
beforeUnmount() {
this.$_timeouts.forEach((timer) => window.clearTimeout(timer));
this.$_intervals.forEach((interval) => window.clearInterval(interval));
this.$_intervals.forEach(([event, callback]) => window.removeEventListener(event, callback));
}
});
Vue.prototype.$setInterval = function (callback, interval) {
this.$_intervals.push(
window.setInterval(callback, interval)
);
}
Vue.prototype.$setTimeout = function (callback, timeout) {
this.$_timeouts.push(
window.setTimeout(callback, timeout)
);
}
Vue.prototype.$addEventListener = function (event, callback, options) {
this.$_listeners.push([event, callback]);
window.addEventListener(event, callback, options);
}
}
}
@gasher
Copy link

gasher commented Jul 16, 2022

I think in VueCleanup.js on line 11 it should be:
this.$_listeners.forEach(([event, callback]) => window.removeEventListener(event, callback)); (notice _listeners instead of _intervals)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment