防抖实现

66 阅读1分钟

连续的事件,只需触发一次回调 防抖应用的场景有:

  • 搜索框搜索输入。只需用户最后一次输入完,再发送请求
  • 手机号、邮箱验证输入检测
  • 窗口大小Resize。只需窗口调整完成后,计算窗口大小。防止重复渲染。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Deounce</title>
</head>
<body>
    <button id="btn">点击</button>
    <script>
        var oBtn = document.getElementById("btn")
        function myDebounce(handle,wait,immefiate){
            // immefiate 控制是第一次执行还是最后一次执行 ,true:第一次执行,false 最后一次执行
            if(typeof handle != 'function') throw new Error('handle must be an function')
            if(typeof wait === 'undefined') wait = 300
            if(typeof wait === 'boolean') {
                immefiate = wait
                wait = 300
            }
            if(typeof immefiate!= 'boolean') immefiate = false
            // 管理handle的执行次数
            // 如果我们想要执行最后一次,那就意味着无论我们当前点击了多少次,都只执行最后一次(搜索输入框控制)
            let timer = null
            
            return function proxy(...args){
                let self = this,
                 init = immefiate && !timer
                if(timer) clearTimeout(timer)
                timer = setTimeout(()=>{
                    timer = null
                    // call 改变this指向
                    !immefiate ? handle.call(self, ...args) : null
                }, wait)
                init ? handle.call(self, ...args) : null
            }
        }
        function btnclick(ev){
            console.log('点击了', ev, this)
        }
        oBtn.onclick = myDebounce(btnclick, 300, false)
        
    </script>
</body>
</html>