防抖

在不断触发情况下,一段时间后才执行

防抖、this、event对象(参数)、是否立即执行、有返回值(在immediate中执行)、可取消

1
2
3
4
5
6
7
function debounce(func, wait) {
var timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(func, wait);
}
}
1
2
3
4
5
6
7
8
9
10
function debounce(func, wait) {
var timeout;
return function() {
var context = this;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context);
}, wait);
}
}
1
2
3
4
5
6
7
8
9
10
11
function debounce(func, wait) {
var timeout;
return function() {
var context = this;
var args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context, args);
}, wait);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this;
var args = arguments;
if (timeout) {
clearTimeout(timeout);
}
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null
}, wait);
if (callNow) {
func.apply(context, args);
}
} else {
timeout = setTimeout(() => {
func.apply(context, args);
}, wait)
}
}
}
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
function debounce(func, wait, immediate) {
var timeout, result;
var debounced = function () {
var context = this;
var args = arguments;
if (timeout) {
clearTimeout(timeout);
}
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(function() {
timeout = null
}, wait);
if (callNow) {
result = func.apply(context, args)
}
} else {
timeout = setTimeout(function() {
func.apply(context, args);
}, wait)
}
return result;
}
debounced.cancel = function () {
clearTimeout(timeout);
timeout = null;
}
return debounced;
}