学学js防抖与节流

163 阅读1分钟

学学js防抖与节流

防抖
  function debounce(fn, t) {
        let time = null;
        return function () {
            if (time !== null) clearTimeout(time);
            // 定时器里面使用箭头函数,如果是匿名函数this => window了
            time = setTimeout(() => {
            // 当前fn => window,使用apply改变指向,并传参
            //也可使用call,fn.call(this, ...arguments) 只是俩者传参方式不同
                fn.apply(this, arguments)
            }, t);
        }
    }
    document.querySelector('input').oninput = debounce(function (e) {
        console.log(e.target.value)
    }, 1000)
节流
    function throttle(fn, t) {
        let Onoff = true;
        return function () {
            if (!Onoff) return false;
            Onoff = false;
            setTimeout(() => {
                fn.apply(this, arguments);
                Onoff = true;
            }, t)
        }
    }
    document.querySelector('input').oninput = throttle(function (e) {
        console.log(e.target.value)
    }, 1000)