File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 函数节流(每隔一段时间执行一次,防止函数过于频繁调用,导致性能问题)
3+ * @param {Function } fn
4+ * @param {number } wait 时间(单位:ms)
5+ * @returns 节流函数
6+ */
7+ export const throttle = ( fn : Function , wait : number = 300 ) => {
8+ let timer = false ;
9+ return ( ...args : any [ ] ) => {
10+ if ( timer ) return ;
11+ timer = true ;
12+ setTimeout ( ( ) => {
13+ fn ( ...args ) ;
14+ timer = false ;
15+ } , wait ) ;
16+ } ;
17+ } ;
18+ /**
19+ * 函数防抖(保证一个函数在多少毫秒内不被再次触发,只会执行一次)
20+ * @param fn 将要处理的函数
21+ * @param wait 事件(单位:ms)
22+ * @param immediate 是否在触发事件后,在时间段n开始,立即执行;否则在时间段n结束,才执行。
23+ * @returns 防抖函数
24+ */
25+ export const debounce = ( fn : Function , wait : number , immediate : boolean = false ) => {
26+ let timer : any = null ;
27+ return ( this : unknown , ...args : any ) => {
28+ if ( timer ) {
29+ clearTimeout ( timer ) ;
30+ timer = null ;
31+ }
32+ if ( immediate ) {
33+ if ( ! timer ) fn . apply ( this , args ) ; // 第一次调用时执行
34+ timer = setTimeout ( ( ) => {
35+ // n秒内多次触发事件,重新计算timer
36+ timer = null ; // n秒内没有触发事件,timer设置为null,保证n秒后能重新触发事件
37+ } , wait ) ;
38+ } else {
39+ timer = setTimeout ( ( ) => {
40+ // 延迟指定毫秒后调用
41+ fn . apply ( this , args ) ;
42+ } , wait ) ;
43+ }
44+ } ;
45+ } ;
You can’t perform that action at this time.
0 commit comments