js实现输入框防抖功能

发布时间 2023-08-03 17:04:42作者: 7c89
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <script>
        let input = document.querySelector("input");
        input.addEventListener('input', debounce(function (e,b) {
            console.log(e);
        }, 3000))
        function debounce(fn, await) {
            //第一个参数是函数,第二个参数时等待的时间
            let timeout = null;
            var args1 = arguments;
            var  count=0;
            //let _that=this
            return function (...args) {
                // console.log(...args1);
                // console.log(this);//这里的this指向当前调用者对象也就是 input
                // console.log(...args);//所有的打印都是为了看清到底是谁被当做参数传递进来了
                //这个地方用课解构es6的新特性,因为不知道会传递几个参数
                //因为第一次定时器为空所以不会进入,当第二次触发也就是用户在此输入的时候就不为空了
                //就会进入判断然后再让定时器为空,直到用户最后一次输入清除以后timeout就有值了就会执行定时器里面的操作了
                if (timeout) {
                    // console.log(this);//这里的this指向当前调用者对象也就是 input
                    //如果timeout有值就清除定时器让定时器从新计时
                    clearTimeout(timeout);
                }else {
                    if(count===0){
                        fn.apply(this, args)
                    }
                    //这个else可有可无,看自己是否需要用户第一次输入的值去做一些操作
                    //这个地方是使用apply改变一下this指向后面的参数就是我们传递的函数
                    //
                }
                timeout = setTimeout(() => {
                    count=1
                    fn.apply(this, args)
                }, await)
            }
        }

    </script>
</body>

</html>