实现节流函数(throttle)
# 时间戳版
function throttle(func, wait) {
var context, args;
var previous = 0;
return function() {
var now = +new Date();
context = this;
args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 定时器版
function throttle(func, wait) {
var context, args;
var timeout = null;
return function () {
context = this;
args = arguments;
if (!timeout) {
func.apply(context, args);
timeout = setTimeout(() => {
timeout = null;
}, wait);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14