There is a better solution!
Debouncing is a technique to frequently restrict the calling of a time-consuming function, by delaying the execution of the function until a specified time to avoid unnecessary CPU cycles, and API calls and improve performance.
You can visit this site for a visual representation of this technique in JS
To implement debounce:
- In helper.js from utilities directory export debounce function
// 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 you must import debounce function and assign it to the variable. I will do the assignment in 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>
- Now connect script to the DOM
<template>
<input type="text" v-model="filterName" @keyup="onKeyup" />
</template>
As a result, by doing the above steps, getUsers() only call once after you stop typing with an 800ms delay.