防抖节流

防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间

 1 function debounce(func, wait) {
 2       var timeout;
 3       return function () {
 4           var _this = this, args = arguments;
 5           timeout && clearTimeout(timeout)
 6           timeout = setTimeout(function(){
 7               func.apply(_this, args)
 8           }, wait);
 9       }
10   }

 

节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

 1 function throttle(func, wait) {
 2     var timeout;
 3     return function() {
 4         var _this = this, args = arguments;
 5         if (!timeout) {
 6             timeout = setTimeout(function(){
 7                 timeout = null;
 8                 func.apply(_this, args)
 9             }, wait)
10         }
11 
12     }
13 }

或者

 1 function throttle(func, wait) {
 2     var previous = 0;
 3     return function() {
 4         var now = Date.now();
 5         var _this = this, args = arguments;
 6         if (now - previous > wait) {
 7             func.apply(_this, args);
 8             previous = now;
 9         }
10     }
11 }

 

posted @ 2019-10-26 23:27  朵拉.科波菲尔  阅读(150)  评论(0编辑  收藏  举报