防抖和节流面试题(4)

一.防抖

1.概念

持续触发不执行,不触发的一段事件后才执行

2.应用场景

根据输入框的内容请求接口

3.生活中的例子

王者荣耀回城

4.封装

const debounce = (fn, time) => {
            let timer = null
            return function (...args) {
                clearTimeout(timer)
                // this => oDiv
                timer = setTimeout(() => {
                    // 干啥!
                    fn.apply(this, args) // 调用的时候传递才是实参,window.fn()
                }, time)
            }
        }

5.建议

lodash.debounce

二.节流

1.概念

持续触发也执行,只不过执行的频率变低了

2.应用场景

滚动条位置的获取

3.生活中的例子

持续按着扳机打散弹枪

4.封装

const throttle = (fn, time) => {
            // #1
            let bBar = true
            return function (e) {
                // #2
                if (!bBar) return
                // #3
                bBar = false
                setTimeout(() => {
                    fn.call(this, e)
                    // #4
                    bBar = true
                }, time)
            }
        }

5.建议

lodash.throttle

猜你喜欢

转载自blog.csdn.net/qq_59076775/article/details/121921801