Skip to content

Commit be4122c

Browse files
committed
feat: throttle function
1 parent aebe6bf commit be4122c

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

js/throttle.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* 节流函数
3+
* @param {Function} fn 需要进行节流函数
4+
* @param {number} delay 节流的时间设置
5+
*/
6+
const throttle = (fn, delay = 500) => {
7+
let flag = true;
8+
return (...args) => {
9+
// 每次调用进来之后,如果flag === false 表示上一次的执行还没有结束,那么不会执行调用函数,直接返回
10+
if (!flag) return;
11+
// 如果flag === true 表示上一次的节流已经执行完了,开始下一次的执行,把flag置为false,表示下次调用节流函数不能执行
12+
flag = false;
13+
setTimeout(() => {
14+
// 执行节流的调用函数,这里注意参数传递和this传递
15+
fn.apply(this, args);
16+
// 函数执行完成之后将flag置为true表示可以进行下一次节流函数的调用
17+
flag = true;
18+
}, delay);
19+
};
20+
};

0 commit comments

Comments
 (0)