js实现输入框防抖功能

<!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))
    input.addEventListener('input', throttle(function (e, b) {
            console.log(e);
        }, 3000,true))
function throttle(fn, delay,once) {
            let timer = null;
            var once1=once

            return function () {
                let context = this;
                let args = arguments;
                if (!timer) {
                    console.log(once1);
                    if(once1){
                        console.log(once1,'---------');
                        fn.apply(context, args);
                        once1=false
                    }
                    timer = setTimeout(function () {
                        fn.apply(context, args);
                        timer = null;
                    }, delay);
                }
            }
        }
        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>
posted @ 2023-08-03 16:59  7c89  阅读(175)  评论(0编辑  收藏  举报