Skip to content

Commit 98c8baa

Browse files
committed
节流函数优化
1 parent eee9148 commit 98c8baa

File tree

1 file changed

+20
-22
lines changed

1 file changed

+20
-22
lines changed

js/others.js

+20-22
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,29 @@
55
*/
66

77
// 节流throttle,多次触发但只执行一部分,(恒时间间距执行)
8-
function throttle(fn, delay) {
9-
var timer = null;
10-
return function () {
11-
var ctx = this;
12-
var args = this.arguments;
13-
if (!timer) {
14-
timer = setTimeout(function () {
15-
timer = null;
16-
fn.apply(ctx, args);
17-
}, delay);
18-
}
19-
}
8+
function throttle(method, threshold, ctx) {
9+
let timer = null;
10+
return function () {
11+
const args = [].slice.call(arguments);
12+
if (!timer) {
13+
timer = setTimeout(function () {
14+
timer = null;
15+
method.apply(ctx, args);
16+
}, threshold);
17+
}
18+
}
2019
}
2120

2221
// 防抖debounce, 多次触发但只执行一次,(时间差大于阈值才执行)
23-
function debounce(fn, delay) {
24-
var timer = null;
25-
return function () {
26-
var ctx = this;
27-
var args = this.arguments;
28-
clearTimeout(timer)
29-
timer = setTimeout(function () {
30-
fn.apply(ctx, args);
31-
}, delay);
32-
}
22+
function debounce(method, threshold, ctx) {
23+
let timer = null;
24+
return function () {
25+
const args = [].slice.call(arguments);
26+
timer && clearTimeout(timer);
27+
timer = setTimeout(function () {
28+
method.apply(ctx, args);
29+
}, threshold);
30+
};
3331
}
3432

3533
// 轮循函数

0 commit comments

Comments
 (0)