对函数防抖的封装

function debounce(fn, delay) {
        let timeId = null;
        return function () {
            //修改this指向
            let that = this;
            let args = arguments;
            
            timeId && clearTimeout(timeId);
            timeId = setTimeout(function () {
                fn.apply(that,args)
            },delay || 1000);
        }
    }

对函数节流的封装

function throttle(fn, delay) {
        let timeId = null;
        let flag = true;
        return function () {
            if (!flag) return
            flag = false
            let that = this;
            let args = arguments;
            timeId && clearTimeout(timeId);
            timeId = setTimeout(function () {
                flag = true
                fn.apply(that,args);
            },delay || 1000);
        }
    }

WanGqD
15 声望0 粉丝