# Vue 中的防抖函数封装和使用
如搜索框中,每改变一个数值就请求一次搜索接口,当快速的改变数值时并不需要多次请求接口,这就需要一个防抖函数:
// 防抖函数
/**
* @param {Function} fun
* @param {number} wait
* @param {boolean} immediate
*/
export function debounce(func, wait, immediate) {
let timeout, result;
return function(...args) {
const context = this;
if (timeout) clearTimeout(timeout);
if (immediate) {
// 如果已经执行过,不再执行
const callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) result = func.apply(context, args);
} else {
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
}
return result;
};
}
// 节流函数
/**
* @param {Function} func
* @param {number} wait
* @param {boolean} immediate
* @return {*}
*/
export function throttle(func, wait, immediate) {
let timeout, context, args, result;
let previous = 0;
const later = function() {
previous = immediate ? 0 : +new Date();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function(...params) {
const now = +new Date();
context = this;
args = params;
if (!previous && immediate) previous = now;
// 距离下次执行还需要等待多长时间
const remaining = wait - (now - previous);
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
//使用:
import { debounce } from "@/common/js/util";
const submitForm = debounce(() => {
getFileUrl().then(() => {
feedback(Object.assign({}, formData)).then(() => {
ifSubmitback.value = true;
});
});
}, 500);
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86