js函数防抖和节流

函数防抖(debounce)

  • 防抖是为了解决频繁触发某个事件的情况造成的性能消耗。
  • 当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定时间到来之前,又触发了事件,就重新开始延时。
 1     /**
 2      * @param func  目标函数
 3      * @param wait  延迟执行毫秒数
 4      * @param immediate true -立即执行,false -延迟执行
 5      * @returns {(function(): void)|*}
 6      */
 7     function debounce(func, wait, immediate) {
 8         let timer;
 9         return function () {
10             let context = this, args = arguments;
11             if (timer) clearTimeout(timer);
12             if (immediate) {
13                 let callNow = !timer;
14                 timer = setTimeout(() => {
15                     timer = null;
16                 }, wait);
17                 if (callNow) func.apply(context, args);
18             } else {
19                 timer = setTimeout(() => {
20                     func.apply(context, args);
21                 }, wait)
22             }
23         }
24     }
View Code

 

函数节流(throttle)

  • 只允许一个函数在xxx毫秒执行一次希望触发的事件handler
  • mustRun属性,代表mustRun毫秒内,必定会触发一次handler。
 1     /**
 2      * @param func  目标函数
 3      * @param wait  延迟时间
 4      * @param mustRun   必定触发一次事件-limited
 5      * @returns {(function(): void)|*}
 6      */
 7     function throttle(func, wait, mustRun) {
 8         let timer, startTime = new Date();
 9         return function () {
10             const context = this, args = arguments, curTime = new Date();
11             clearTimeout(timer);
12             if (curTime - startTime >= mustRun) {
13                 func.apply(context, args);
14                 startTime = curTime;
15             } else {
16                 timer = setTimeout(func, wait);
17             }
18         }
19     }
View Code

  假设wait=500,mustRun=1000,则表示在一段时间内事件触发的间隔一直短于500ms,那么保证在1000ms内handler至少执行一次。

posted @ 2021-09-26 11:14  亦茫茫  阅读(31)  评论(0编辑  收藏  举报