【干貨】防抖與節(jié)流

廢話不多說,開箱即用

# HTML

<h2>防抖與節(jié)流</h2>

<input class="antiShake" placeholder="請輸入-防抖">

<div class="throttle">節(jié)流</div>

# 防抖

/**
 * @func 防抖:用戶短時間內(nèi)多次觸發(fā)請求,只發(fā)起最后一次,將多個請求變成一次
 * @desc 核心:一定時間內(nèi)沒有繼續(xù)操作后執(zhí)行處理函數(shù)。時間范圍內(nèi)只要來新請求,立刻取消上一次操作。新請求比老請求更有業(yè)務(wù)價值
 * @desc 經(jīng)典案例:模糊搜索
 */
let telInput = document.querySelector('.antiShake')

// 未防抖情形
// telInput.addEventListener('input', (e) => {
//     request()
// })

// 加了防抖 - antiShake通過閉包返回了函數(shù)
telInput.addEventListener('input', antiShake(request, 2000))

// 防抖函數(shù) (本案例利用閉包實現(xiàn),這樣無需再antiShake外部定義timeout變量)
function antiShake(fn, wait) {
    let timeout = null
    return args => {
        if (timeout) clearTimeout(timeout)
        timeout = setTimeout(fn, wait)
    }
}

function request() {
    console.log('發(fā)起請求了')
}

# 節(jié)流

/**
 * @func 節(jié)流:用戶的某些操作導(dǎo)致重復(fù)的發(fā)起相同的請求,只發(fā)起第一次
 * @desc 應(yīng)用場景:提交表單,點擊提交按鈕,告片的監(jiān)聽事件如touchmove
 */
let box = document.querySelector('.throttle')

// 未節(jié)流情形
// box.addEventListener('touchmove', (e) => {
//     request()
// })

// 加了節(jié)流:
box.addEventListener('touchmove', throttle(request, 2000))

// 節(jié)流函數(shù):觸發(fā)后開始計時,時間間隔內(nèi)再過來的請求直接忽略,計時完成執(zhí)行函數(shù)后,再接收下一個請求
function throttle(event, wait) {
    let timer = null
    return args => {
        if (!timer) {
            timer = setTimeout(() => {
                event()
                timer = null
            }, wait)
        }
    }
}

function request() {
    console.log('發(fā)起請求了')
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容