Skip to content

Instantly share code, notes, and snippets.

@gangsthub
Last active November 29, 2021 19:02
Show Gist options
  • Save gangsthub/360b782e6f3e3e6667826fc65f420d22 to your computer and use it in GitHub Desktop.
Save gangsthub/360b782e6f3e3e6667826fc65f420d22 to your computer and use it in GitHub Desktop.
Simple Debounce Vue 2 Mixin: `simple-debounce-vue-mixin`

SimpleDebounce (Vue Mixin)

If you are listening to changes on an Event (DOM Events) to execute any side effects like performing network requests, you'd probably want to "debounce" your attached function executions.

This is an alternative to lodash.debounce but "vanilla js" packed as a Vue SFC to import it as a mixin.

The default debouncing time is 300ms.

By default each time it's invoked it creates a setTimeout reference that will be cleared when the component is destroyed to prevent memory leaks.

📦 Install

npm i -S gist:360b782e6f3e3e6667826fc65f420d22	

Usage:

<script>
import simpleDebounce from 'simple-debounce-vue-mixin'
// ...
export default {
  mixins: [simpleDebounce],
  methods: {
    inputHandler($event) {
      this.simpleDebounce(() => {
        // do something here with `$event`...
        // like fetching auto-complete values...
        // or updating internal model...
      }, 350 /* optional debounce time: default is 300 */)
    }
  }
}
</script>
{
"name": "simple-debounce-vue-mixin",
"version": "1.0.2",
"main": "simple-debounce-vue-mixin.js"
}
export default {
data() {
return {
timerId: null,
}
},
methods: {
/**
* @param {(arg0?: any) => void} fn
* @param {number} delay
*/
simpleDebounce(fn, delay = 300) {
// caveat: only 1 timeout at a time because of the timerId;
// that's why we leave this inside the component scope
// and not as a global utility
return ((...args) => {
// only in browser
clearTimeout(this.timerId)
this.timerId = setTimeout(() => {
this.timerId = null
fn(...args)
}, delay)
})()
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment