Discover a superior solution!
Debouncing is a clever technique that limits the frequent execution of a time-consuming function by postponing its call until a specific time, thus preventing unnecessary CPU cycles, API calls, and enhancing performance.
To see a visual demonstration of this concept in JavaScript, check out this resource
To apply debouncing:
- In the utilities directory, export the debounce function from helper.js file
// utilities/helper.js
export const debounce = (func, delay = 600, immediate = false) => {
let timeout
return function () {
const context = this
const args = arguments
const later = function () {
timeout = null
if (!immediate) func.apply(context, args)
}
const callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, delay)
if (callNow) func.apply(context, args)
}
}
- In your component, import the debounce function and assign it to a variable within mounted()
<script>
import { debounce } from '~/utilities/helper'
export default {
name: 'MyComponent',
data() {
return {
debounceFn: null,
filterName: ''
}
},
mounted() {
this.debounceFn = debounce(() => this.getUsers(), 800)
},
methods: {
onKeyup() {
this.debounceFn()
},
getUsers() {
// Logic
}
}
}
</script>
- Connect the script with the DOM
<template>
<input type="text" v-model="filterName" @keyup="onKeyup" />
</template>
Following these steps will ensure that getUsers() is only called once after you have stopped typing, with an 800ms delay.