关于javascript:JavaScript-一起了解防抖和节流

7次阅读

共计 1577 个字符,预计需要花费 4 分钟才能阅读完成。


概念

函数防抖和函数节流,两者都是优化高频率执行 js 代码的一种伎俩。

防抖

概念 : 所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会从新计算函数执行工夫。

<button id="debounce"> 点我防抖!</button>

$('#debounce').on('click', debounce());

function debounce() {
    let timer;
    return function () {clearTimeout(timer);
        timer = setTimeout(() => {
            // 须要防抖的操作...
            console.log("防抖胜利!");
        }, 500);
    }
}

函数防抖的利用场景,最常见的就是页面滚动条监听的例子,来进行解析:

let timer;
window.onscroll = function () {clearTimeout(timer);
    timer = setTimeout(function () {
        // 滚动条地位
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        console.log('滚动条地位:' + scrollTop);
    }, 200)
}

防抖函数的封装应用

/**
 * 防抖函数
 * @param fn 事件触发的操作
 * @param delay 多少毫秒内间断触发事件,不会执行
 * @returns {Function}
 */
function debounce(fn,delay) {
    let timer = null;
    return function () {
        let self = this,
            args = arguments;
        timer && clearTimeout(timer);
        timer = setTimeout(function () {fn.apply(self,args);
        },delay);
    }
}

window.onscroll = debounce(function () {
    let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    console.log('滚动条地位:' + scrollTop);
},200)

节流

概念: 指定工夫距离内只会执行一次工作(肯定工夫内 js 办法只跑一次)

<button id="throttle"> 点我节流!</button>

$('#throttle').on('click', throttle());

function throttle(fn) {
    let flag = true;
    return function () {if (!flag) {return;}
        flag = false;
        setTimeout(() => {console.log("节流胜利!");
            flag = true;
        }, 1000);
    };
}

图片形容:

函数节流利用的理论场景,依据文本框中输出的内容主动申请后盾数据

上面是节流函数的封装与应用:

<input type="text" value=""id="input">

$('#input').on('keyup', throttle(function () {console.log($(this).val());
    // ajax 后盾申请....
}, 1000));

/**
 * 节流函数
 * @param fn 事件触发的操作
 * @param delay 距离多少毫秒须要触发一次事件
 */
function throttle(fn, delay) {
    let flag = true;
    return function () {
        let self = this,
            args = arguments;
        if (!flag) {return;}
        flag = false;
        setTimeout(() => {fn.apply(self, args);
            flag = true;
        }, delay);
    }
}

正文完
 0