防抖和节流

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 <body>
10     <button id="btn">定时器</button>
11 </body>
12 <script src="../js/debounce2.js"></script>
13 </html>
debounce2.js
 1 /*
 2    函数的防抖(防止老年帕金森):对于频繁触发某个操作,我们只识别一次(只触发执行一次函数)
 3    @params
 4       func[function]:最后要触发执行的函数
 5       wait[number]:"频繁"设定的界限
 6       immediate[boolean]:默认多次操作,我们识别的是最后一次,但是immediate=true,让其识别第一次
 7    @return 
 8      可以被调用执行的函数
 9 
10    主体思路:在当前点击完成后,我们等wait这么长的时间,看是否还会触发第二次,如果没有触发第二次
11    属于非频繁操作,我们直接执行想要的执行的函数func,如果触发了第二次,则以前的不算了,从当前这
12    次在开始等待.....
13 */
14 function debounce(func, wait = 300, immediate = false) {
15   var timer = null;
16   return function anonymous(...params) {
17     let now = immediate && !timer;
18 
19     //每次点击都把设置的定时器清除
20     clearTimeout(timer);
21 
22     //重新设置一个新的定时器监听wait时间内是否触发第二次
23     timer = setTimeout(() => {
24       //手动让其回归到初始状态
25       timer = null;
26 
27       //wait 这么久的等待中,没有触发第二次
28       !immediate ? func.call(this, ...params) : null;
29     }, wait);
30 
31     //如果是立即执行
32     now ? func.call(this, ...params) : null;
33   };
34 }
35 
36 /*
37 函数节流:在一段频繁的操作中,可以触发多次,但是触发的频率由自己决定 
38    @params
39       func[function]:最后要触发执行的函数
40       wait[number]:"频繁"设定的界限
41    @return 
42      可以被调用执行的函数 
43 */
44 
45 //节流1
46 function throttle(func, wait = 300) {
47   let timer = null,
48     previous = 0; //记录上一次的操作时间
49   return function anonymous(...params) {
50     let now = new Date(),
51       remaining = wait - (now - previous); //记录还差多久达到我们一次触发的频率
52     if (remaining <= 0) {
53       //两次操作的时间间隔超过wait了
54       clearTimeout(timer);
55       timer = null;
56       previous = now;
57       func.call(this, ...params);
58     } else if (!timer) {
59       //两次操作的时间还不符合触发的频率
60       timer = setTimeout(() => {
61         timer = null;
62         previous = new Date();
63         func.call(this, ...params);
64       }, remaining);
65     }
66   };
67 }
68 
69 //节流2
70 function throttle2(func, wait=300) {
71     var begin = 0;
72     return function () {
73         var cur = new Date().getTime();
74         if (cur - begin > wait) {
75             func.apply(this, arguments)
76             begin = cur;
77         }
78     }
79 }
80 
81 function fun() {
82   console.log("定时器执行");
83 }
84 
85 btn.onclick = throttle(fun, 1000);

 

 
posted @ 2021-05-03 11:52  神奇的小胖子  阅读(61)  评论(0编辑  收藏  举报