标签:频率 set argument 事件触发 out arguments clear app ott
防抖:触发高频事件后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 }
标签:频率 set argument 事件触发 out arguments clear app ott
原文地址:https://www.cnblogs.com/vicky24k/p/11746264.html