JS封装一个防抖函数与节流函数

防抖函数

// 防抖
function debounce(fn, delay = 500) {
    // timer 是闭包中的
    let timer = null
    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments) 
            timer = null
        }, delay)
    }
}

节流函数

// 节流
function throttle(fn, delay = 100) {
    // timer 是闭包中的
    let timer = null
    return function () {
        if (timer) {
            return
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}

你可能感兴趣的:(JS封装一个防抖函数与节流函数)