节流和防抖

徐徐
前端
发表于 2024/04/15 16:00
🌺 摘要
给出节流与防抖两段实现代码,对比触发时机与调用频率控制方式,便于在输入监听和滚动场景中选型。

节流和防抖

节流

function debounce(fn, wait) {
     let timer = null
        return function () {
           if (timer) clearTimeout(timer)
                timer = setTimeout(() => {
                    fn.call(this, arguments)
                }, wait)
            }
        }

防抖

function throttle(fn, wait) {
            let timer = null
            return function () {
                if (!timer) {
                    timer = setTimeout(() => {
                        event()
                        timer = null
                    }, wait)

                }
            }
        }
文章发表于 2024/04/15 16:00
作者: 徐徐
文章标题: 节流和防抖
版权声明: 内容遵守许可协议,转载请注明出处。
扫码阅读原文

评论

加载中...