函数节流和防抖

1.函数节流

  函数在时间间隔内只能被触发一次。

  函数节流有两种方式:

    (1)第一次执行:

throttle(function,delay) {
    let timer = null;
    let first = true;
    let that = this;
    let args = arguments;
    return () => {
        if(first === false) {
            function.apply(this,function);
            return first = false;
        }
        if(timer) {
            return;
        }
        timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
function.apply(that,args); },delay) } }

    (2)第一次不执行,delay之后再执行:

throttle(function,delay) {
    let timer = null;
    let that = this;
    let args = arguments;
    return () => {
        if(timer) {
            return;
        }
        timer = setTimeout(() => {
            clearTimeout(timer);
            timer = null;
            function.apply(that,args);
        },delay)
    }
}

2.函数防抖

  触发函数后一定时间后执行,但如果等待这段时间又被触发则重新开始计时。

debounce(function,delay) {
    let timer = null;
    let that = this;
    let args = arguments;
    return () => {
        if(timer) {
            clearTimeout(timeout);
        }
        timer = setTimeout(() => {
            function.apply(that,args);
        },delay);
    }
}
posted @ 2021-05-21 16:42  桃李子  阅读(48)  评论(0编辑  收藏  举报