什么是防抖debounce?

327 阅读1分钟

什么是防抖debounce?

防抖(debounce):就是让某个函数在上一次执行之后,满足等待某个时间内不再触发此函数后再执行,而在这个等待时间内再次触发函数,等待时间可以重新计算,知道该函数在一定间隔内没有被调用时,才开始执行被调用方法(所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。),进入电梯事件就可以理解成防抖

应用场景

应用场景:用户注册时候的手机号验证和邮箱验证

写法

const input1 = document.getElementById("input1");
        let timer = null;
        input1.addEventListener('keyup', function() {
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(function() {
                // 模拟事件  change 事件
                console.log(input1.value);

                // 清空定时器
                timer = null;
            },800)
        })

封装轮子

const input1 = document.getElementById("input1");
function debounce(fn, delay = 500) {
            // timer 是闭包中的
            let timer = null;
            
            return function() {
                if (timer) {
                    clearTimeout(timer);
                }
                timer = setTimeout(() => {
                    fn()
                    timer = null;
                }, delay);
            }
        }

        input1.addEventListener('keyup', debounce(function() {
            console.log(input1.value);
        }))