js防抖与节流

 直接上代码

防抖:

export function onDeb(fn, delay = 300) {
    let timer;
    return function () {
        clearTimeout(timer);
        let context = this;
        let args = arguments; 
        timer = setTimeout(function () {
            fn.call(context, args);
        }, delay);
    };
}

节流:

export function onThro(fn, delay = 300) {
    let enterTime = 0;//触发的时间
    return function () {
        let context = this;
        let backTime = new Date();//第一次函数return即触发的时间
        if (backTime - enterTime > delay) {
            fn.call(context, arguments);
            enterTime = backTime; 
        }
    };
}

你可能感兴趣的:(javascript,前端,开发语言)