首页 > Web开发 > 详细

函数的防抖---js

时间:2019-12-08 15:36:39      阅读:102      评论:0      收藏:0      [点我收藏+]
执行规定一段时间后执行
    <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>

 

函数的防抖---js

原文:https://www.cnblogs.com/PasserByOne/p/12005742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!