转载于:https://blog.csdn.net/Ted_az/article/details/127018974

1.防抖(debounce)函数

防抖是触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。适用于可以多次触发但触发只生效最后一次的场景。

设计思路:调用函数不立即执行,而是等待一段时间后再执行

 

 1 /*
 2  * @param  {function}   func      回调函数
 3  * @param  {number}     wait      表示时间间隔
 4  * @param  {boolean}    immediate  如果为true则为立即执行,为false则为延迟执行                             
 5  * @return {function}             返回客户调用函数
 6  */
 7 function debounce(func,wait,immediate) {
 8     let timeout,result; // timeout 为计时器,result为回调函数的返回值
 9     let debounced = function() {
10         if(timeout)clearTimeout(timeout); // 如果计时器存在,要将其清除,以便重新建立新的计时器(防抖的核心)
11         let context = this; // 暂存debounced的this指向,其指向响应函数,方便后续改变func的this指向
12         let args = arguments; // 暂存响应函数的event参数,以便后续将其赋给fun
13         if(immediate) {
14             let flag = !timeout; // 判断此时是否还在上一个计时中
15             timeout = setTimeout(function(){
16                 timeout = null;
17             },wait);   // 设定计时器,在wait时间之后,把计时器赋为空,以便那时能立即执行
18             if(flag) result = func.apply(context,args); // 若满足条件,则立即执行
19         }else {
20             // 不是立即执行模式则设置延迟执行函数
21             timeout = setTimeout(function() {
22                 func.apply(context,args);
23             },wait);  
24         }
25         return result;
26     }
27     // 取消计时器的操作
28     debounced.cancel = function() {
29         clearTimeout(timeout);
30         timeout = null;
31     }
32     return debounced;
33 }

 

2.节流(throttle)函数

节流是高频事件触发,但在n秒内只会执行一次,如果n秒内触发多次函数,只有一次生效,节流会稀释函数的执行频率。

 

/*
 * @param  {function}   func      回调函数
 * @param  {number}     wait      表示时间窗口的间隔
 * @param  {object}     options   如果想忽略开始函数的的调用,传入{leading: false}。
 *                                如果想忽略结尾函数的调用,传入{trailing: false}
 *                                两者不能共存,否则函数不能执行
 * @return {function}             返回客户调用函数
 */
function throttle(func, wait, options) {
    let context, args, timeout;
    let old = 0; // 时间戳
    if (!options) options = {}; // 如果没有该参数,则置为0,防止意外发生
    return function () {
        context = this;
        args = arguments;
        let now = new Date().valueOf();
        if (options.leading === false && old == 0) old = now; // 不要立即执行,则第一次不会进入if(now-old>wait)
        if (now - old > wait) {   // 当时间间隔达到一个周期则执行此代码块
            // 第一次会直接执行
            if (timeout) {            // 将计时器清除,防止执行两次响应函数
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context, args);
            old = now;
        } else if (!timeout && options.trailing !== false) { // 当时间间隔未达到一个周期时则执行此代码块
            // 最后一次被执行
            timeout = setTimeout(function() {  // 在一般情况下是不会执行这个延迟函数的,只有在最后一次执行此延迟函数
                old = new Date().valueOf();    // 在最后一次执行时候将old置为当前时间,防止下一次操作响应的时间间隔不足wait
                timeout = null;
                func.apply(context, args);
            }, wait)
        }
    }
}

 

posted on 2023-04-21 10:52  皮五辣子  阅读(263)  评论(0编辑  收藏  举报