美文网首页
防抖函数和节流函数

防抖函数和节流函数

作者: 摸爬打滚 | 来源:发表于2021-10-22 15:12 被阅读0次

防抖函数

  • 会定义多个定时器,并且在定义下个定时器的时候清楚上一个定时器
  • 连续触发后只会执行第一次或者最后一次函数
  • 高频触发只会执行一次函数
// handle 表示点击事件的函数
// wait 表示多久触发一次handle
// immediate 表示连续点击了按钮之后,true表示第一次触发handle, false表示最后一次触发handle
function myDebounce(handle, wait, immediate) {
    // 判断参数
    if (typeof handle === 'function') throw new Error('hanndle must be function');
    if (typeof wait === 'undefined') wait = 300;
    if (typeof wait === 'boolean') {
        immediate = wait;
        wait = 300;
    }

    // 设置一个变量用来保存延时处理的内容
    let timer = null;

    // 重新返回一个函数(防止多次触发handle函数)
    return function proxy(...args) {
        // 每次点击按钮首先要清空当前的timer,每次清除的都是上一次的timer
        clearTimeout(timer);
        // 定义一个变量用来存放选择第一次触发。(1、首先要判断immediate是否为true,2、然后看判断timer当前是不是null)满足前面2点,则立马执行handle
        let init = immediate && !timer;
        // 定义一个延迟函数放在timer中,便于后期清除timer(为了不执行立马内容)
        timer = setTimeout(() => {
            // 需要把timer清空
            timer = null;
            // 执行最后一次的需要再此处执行handle
            !immediate ? handle.call(this, ...args) : null;
        }, wait);
        //执行第一次的需要在此次执行handle(执行完handle后,会在wait秒数后将timer清空)
        init ? handle.call(this, ...args) : null;
    }
}

节流函数

  • 只会定义一个计时器,当前有定时器时不会重新定义定时器。
  • 连续触发时会计算上次执行函数时间(a)到现在触发的时间(b)是否达到了规定的时间间距(wait)c = b - a :
    • 达到(c >= wait):执行函数
    • 未达到(c < wait):判断是否有一个未执行的定时器:
      • 有:退出
      • 无:定义一个定时器,把剩下的时间间距作为定时器的延迟时间(延迟时间 = wait - c)
  • 高频触发会在一段时间内执行一次
function myThrottle(handle, wait) {
    // 参数校验
    if (typeof handle !== 'function') throw new Error('Handle must be a function');
    if (wait === 'undefined') wait = 300;

    // 定义一个字段用于存放上次执行handle的时间
    let lastTime = 0;
    // 定义一个字段存放延时函数
    let time = null;

    // 返回一个新的执行函数
    return function proxy(...args) {
        let nowTime = new Date();
        let timeDifference = wait - (nowTime - lastTime) // lastTime为0时,第一次肯定可以执行
        if (timeDifference <= 0) {
            clearTimeout(time);
            time = null;

            handle.call(this, ...args); // this值得是执行的函数本身
            lastTime = new Date(); // 记录执行时间
        } else if (!time) { // 假如time已经有值,则不用执行后面操作,只赋值一次
            time = setTimeout(() => {
                clearTimeout(time);
                time = null;
    
                handle.call(this, ...args);
                lastTime = new Date(); 
            }, timeDifference) // 注意:这里不应该是wait,而是距离上次执行相差的时间!!!!
        }
    }
}

相关文章

网友评论

      本文标题:防抖函数和节流函数

      本文链接:https://www.haomeiwen.com/subject/hhzcaltx.html