函数防抖与函数节流

debounce

定义:如果一个函数持续地触发,那么只在它结束后过一段时间执行一次。

基本实现:

function debounce(func, delay = 500) {
    var timeout;
    return function (e) {
        clearTimeout(timeout);
        var context = this,
            args = arguments;
        timeout = setTimeout(function () {
            func.apply(context, args);
        }, delay)
    };
};
var func = debounce(function (v) {
    console.log('--', v)
});

var i = 0;
function change() {
    func(i);
    setTimeout(() => {
        i < 10 && change();
    }, i*100);
    i++;
}
change();
// 5,6,7,8,9

throttle

定义:如果一个函数持续的,频繁地触发,那么让它在一定的时间间隔后再触发

Last updated

Was this helpful?