0 day streak
javascript / beginner
Snippet

Debouncing Search Input with SetTimeout in Vue

Debouncing is a performance pattern that limits the rate at which a function gets called. By clearing the previous timer on each keystroke and setting a new setTimeout, the reactive search query only updates after the user pauses typing for 300 milliseconds.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref } from 'vue';
export default {
setup() {
const searchQuery = ref('');
let debounceTimer = null;
function onSearchInput(event) {
const query = event.target.value;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
searchQuery.value = query;
}, 300);
}
return { searchQuery, onSearchInput };
}
};
vue
Breakdown
1
clearTimeout(debounceTimer);
Cancels any pending timer from previous keystrokes to prevent premature updates.
2
debounceTimer = setTimeout(() => { ... }, 300);
Schedules the reactive update to execute 300ms after the last input event.