π’ Debouncing in Vue
There are multiple ways how you can implement debouncing in Vue so let's start from the easiest one - pure JavaScript. There is a built in method in JS called setTimeout that allows you to trigger some functionality after certain period of time. We can use it in our debounce method like following:
export function debounce(fn, wait){
let timer;
return function(...args){
if(timer) {
clearTimeout(timer); // clear any pre-existing timer
}
const context = this; // get the current context
timer = setTimeout(()=>{
fn.apply(context, args); // call the function if time expires
}, wait);
}
}
As mentioned, this is a pure JS solution that will work nicely. But there might be some cases where you may want to have someting more Vue specific like having access to reactive properties that will be updated automatically like ref or computed. For that, you may want to try out VueUse and more specifically the useDebounceFn composable:
import { useDebounceFn } from '@vueuse/core'
const debouncedFn = useDebounceFn(() => {
// do something
}, 1000)
window.addEventListener('resize', debouncedFn)
You can read more about this composable here.
π Learn more
There is a great course about VueUse from Vue School that you can check out with this link or by clicking the image below:
Vue School Link
It covers most important composables to help you handle browser, sensors, animation and other useful utilities in an easy and Vue-like way π
β
Summary
Well done! You have just learned about the concept of debouncing and how you can utilize it in Vue to trigger some functionality after certain amount of time.
Take care and see you next time!
And happy coding as always π₯οΈ