js | 防抖&&节流


正常:事件触发非常频繁,每一次触发,回调函数都会执行,如果时间很短,回调函数中有计算,有可能会出现浏览器卡顿

防抖:前面所有的触发都会取消,最后一次的执行在规定的时间之后才会触发频繁触 => 只执行一次

节流:在规定的时间间隔范围内,不会触发多次回调,只有大于这个时间才会触发回调。频繁触发 => 少量触发

实现方式:
1、可以使用第三方 lodash 插件【lodash向外暴露的是_.+函数名()】
_.debounce(fn,waitTime,option)  // 防抖
_.throttle(fn,waitTime,option)  // 节流

2、自己封装

//防抖
function debounce(fn, delay) {
    let timer = null
    const _debounce = function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn()
        }, delay) }
    return _debounce
}
//节流
function throttle(fn, interval) {
    let lastTime = 0
    const _throttle = function () {
        const nowTime = new Date().getTime()
        // console.log(new Date(nowTime));
        const remainTime = interval - (nowTime - lastTime)
        if (remainTime <= 0) {
            fn() lastTime = nowTime
        }
    }
    return _throttle
}

 

posted @ 2022-08-13 19:30  三水儿  阅读(45)  评论(0编辑  收藏  举报