简洁高效,让你认清 防抖和节流;

 /*
        *  fn -- 用户传入函数
        *  timer -- 用户传入间隔时间
        *  debounce_防抖作用:防止用户反复点击,比如提交表单,浏览器滚动监听等,当用户停止点击时候,间隔时间大于timer,则执行传入函数;
        *  throttle_节流作用:监听事件在timer规定时间内只执行一次,达到节流作用;
        */ 
        function debounce_(fn,timer){
            return function(){
                clearTimeout(fn.id);
                var that = this;
                fn.id = setTimeout(function(){
                    fn.constructor == Function && fn.call(that);  //这样可以获取到点击事件源, 
                    // fn()     //这样也可以运行,
                },timer);
            }
        };
        function throttle_(fn,timer){
            var initTimer = new Date();            var first = true;   //因为第一次判定时候当前时间和初始时间也许相等,差值也许会小于我们给定的timer,程序不会执行,所以加上这个好些;
            return function(){  //采用闭包
            var nowTimer = new Date();   
                if( nowTimer - initTimer  >= timer || first){
                    fn.constructor == Function && fn.call(this);  //判断fn是否为函数;是的话就执行 fn.call(this);
                    initTimer = new Date();
                    first = false;
                }
            }
        }
        function test(){
            console.log('test');
        }
        document.querySelector('button').addEventListener('click',throttle_(test,2000));  //节流
        // document.querySelector('button').addEventListener('click',debounce_(test,300));  //防抖
posted @ 2020-04-15 10:24  忧伤还是快乐i  阅读(159)  评论(0编辑  收藏  举报