debounce, delay in events in Vue 3

Video thumbnail

Currently, the local filter works perfectly and is fast, since it operates locally (localhost). However, if this application connects to the internet or is hosted online, you'll encounter performance and efficiency issues.

The main problem is that you're sending too many requests to the server: every time you type something (every keystroke), a request is sent. This not only unnecessarily overloads the server but can also crash the application, especially since a filter doesn't need to be so instantaneous.

⏳ The Solution: Implement Debouncing

In these cases, the common practice is to implement debouncing. This involves introducing a waiting period or grace period after the user stops typing. The request is only sent once this time has elapsed, allowing the user to quickly type their complete sentence and saving multiple requests to the server.

We need to use a plugin like the following:

https://www.npmjs.com/package/vue-debounce

Which we install with:

$ npm i vue-debounce

️ Global Implementation with vue-debounce

And we configure:

resources/js/app.js

import vueDebounce from 'vue-debounce';
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

app
 .directive('debounce', vueDebounce({ lock: true })) // Se registra como una directiva llamada 'debounce'
 .mount('#app');

To use it, we have several ways as you can review in the official documentation, but, as we are only interested in applying to a single field, we can use the following implementation:

resources/js/Pages/Dashboard/Post/Index.vue

<TextInput 
    autofocus 
    v-debounce.500ms="customSearch" 
    :debounce-events="['keyup']" 
    class="w-full" 
    type="text" 
    placeholder="Search..." 
    v-model="search" 
/>

Syntax Explanation

  • v-debounce.500ms="customSearch": The key part. It indicates that we want to call the customSearch function after 500 milliseconds of inactivity.
  • :debounce-events="['keyup']": It indicates the event that the plugin should "listen" for to start the countdown. In this case, the event is keyup (when the key is released).
v-debounce.500ms="customSearch"

Although it can be applied to for example seconds:

v-debounce.1s="customSearch"

And what are the events we want to hear:

:debounce-events="['keyup']"

After reloading the application and starting to type, you'll notice that the search function (customSearch) is only called after you've stopped typing for the specified time. This optimizes the process and drastically reduces server calls.

With this, we've completed the filters and search field applied to our application.

Learn how to delay the execution of events when writing to a search field in Vue 3.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español