1. 程式人生 > 資訊 >快手針對直播炒作開展專項治理

快手針對直播炒作開展專項治理

// 第一版
// 缺點:函式的 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