108-js-24-手写debounce

概述

输入框中防止连续触发事件,用户输入结束或暂停时再触发

示例

const input1 = document.getElementById('input1')

let timer = null
input1.addEventListener('keyup', function () {
    if (timer) {
        clearTimeout(timer)
    }
    timer = setTimeout(() => {
        // 模拟触发 change 事件
        console.log(input1.value)

        // 清空定时器
        timer = null
    }, 500)
})
const input1 = document.getElementById('input1')

// 防抖
function debounce(fn, delay = 500) {
    // timer 是闭包中的
    let timer = null

    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}

input1.addEventListener('keyup', debounce(function (e) {
    console.log(e.target)
    console.log(input1.value)
}, 600))