Debounce Function in Vue - Implementation and Usage
# Debounce Function in Vue - Implementation and Usage
For example, in a search box where every value change triggers a search API call, you don't need multiple API calls when the value changes rapidly. This is where a debounce function is needed:
// Debounce function
export function debounce(func, delay) { // func: function, delay: interval time
let timer
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}
// Usage:
import { debounce } from '@/common/js/util'
created() {
/**
* Why not write this directly in a watcher???
* Because debounce handling is needed to prevent
* multiple API calls during rapid input
*/
this.$watch('query', debounce((newQuery) => {
this.$emit('query', newQuery)
}, 200))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Related Articles
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36