Blog>
Snippets

Debouncing Input Handlers

Provide an example of how to debounce user input in Vue.js 3 to limit the rate at which a function that updates the data/model is invoked.
<template>
  <input v-model="input" @input="debouncedInputHandler" />
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const input = ref('');
    let timeout;

    // Debounce function
    function debouncedInputHandler(event) {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        // Function that updates the data/model
        input.value = event.target.value;
      }, 500); // 500ms debounce time
    }

    // Expose to the template
    return { input, debouncedInputHandler };
  },
};
</script>
This Vue.js 3 component template contains an input element that utilizes a debounced input handler. The 'debounce' effect is achieved by using a timeout to delay the execution of the actual input handler function. When a user types in the input field, the 'debouncedInputHandler' function is triggered, and it clears any existing timeouts, then sets a new one to update the input value after a delay of 500 milliseconds. This approach ensures that the actual input update function is not called on every key press, but rather after the user has stopped typing for the specified delay, reducing the frequency of expensive input handling operations.