js 防抖节流

// 第一版
// 缺点:函数的 this 指向了 window,应该指向 container
function debounce1(fn, wait) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(fn, wait);
    }
}

// 第二版(解决this指向问题)
// 缺点:函数的事件对象 event 变成了 undefined
function debounce2(fn, wait) {
    let timer;
    return function () {
        clearTimeout(timer);
        // console.log(this);  // 这里的 this 是对的
        timer = setTimeout(() => {
            fn.call(this)    //绑定上面的 this
        }, wait);
    }
}


// 第三版(解决 event 事件对象问题)
function debounce(fn, wait) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, arguments)   // 把参数传进去
        }, wait);
    }
}


// 第四版(立即执行,停止触发 n 秒后,才可以重新触发执行。反过来)
function debounce4(fn, wait, immediate) {
    let timer;
    return function () {
        if (timer) clearTimeout(timer);
        if (immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            if (callNow) {
                fn.apply(this, arguments)
            }
        } else {
            timer = setTimeout(() => {
                fn.apply(this, arguments)
            }, wait);
        }
    }
}

// 在 vue 中使用(注意:不能使用箭头函数,否则this指向不对)
// move: debounce(function () {
//     console.log(this.title);
// }, 1000)


参考链接:https://blog.csdn.net/time_____/article/details/114326156

posted @ 2022-04-18 15:48  智商感人  阅读(34)  评论(0)    收藏  举报