函数的防抖---js

执行规定一段时间后执行
    <input type="text" id="inp" />
    <script>
        var oInp = document.getElementById("inp")
        var timer = null;

        function ajax(e) {  // 需要执行的函数
            console.log(this.value);  
        }
        oInp.oninput = function(e) {
            clearTimeout(timer);  // 结束上一次的定时器
            var _this = this, _argm = arguments
            timer = setTimeout(function() {   // 1000ms后执行定时器内的事件
                ajax.apply(_this, _argm)   // 使用apply将this指向到该函数内
            }, 1000)
        }
    </script>

 将该功能封装成一个还是

    <input type="text" id="inp" />
    <script>   
        var oInp = document.getElementById("inp")
        var timer = null;

        function ajax(e) { // 需要执行的函数
            console.log(this.value, e);
        }

        function debounce(handler, delay) { //封装防抖
            var timer = null;
            return function() {
                var _this = this,
                    _argm = arguments;
                clearTimeout(timer)
                timer = setTimeout(function() {
                    handler.apply(_this, _argm)
                }, delay)
            }
        }

        oInp.oninput = debounce(ajax, 1000)  
     </script>

猜你喜欢

转载自www.cnblogs.com/PasserByOne/p/12005742.html