函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
1 /** 2 * @desc 函数防抖 3 * @param fn 函数 4 * @param delay 延迟执行毫秒数 默认0.5s 5 */ 6 export function debounce(fn, delay) { 7 var delay = delay || 500; 8 var timer; 9 return function () { 10 console.log('调用了debounce方法') 11 let args = arguments; 12 if(timer){ 13 clearTimeout(timer); 14 } 15 timer = setTimeout(() => { 16 timer = null; 17 fn.apply(this, args); 18 }, delay); 19 } 20 } 21 22 /** 23 * @desc 函数节流 24 * @param fn 函数 25 * @param interval 函数执行间隔时间毫秒数 默认1s 26 */ 27 export function throttle(fn, interval) { 28 var last; 29 var timer; 30 var interval = interval || 1000; 31 return function () { 32 console.log('调用了throttle方法') 33 var th = this; 34 var args = arguments; 35 var now = +new Date(); 36 if (last && now - last < interval) { 37 clearTimeout(timer); 38 timer = setTimeout(function () { 39 last = now; 40 fn.apply(th, args); 41 }, interval); 42 } else { 43 last = now; 44 fn.apply(th, args); 45 } 46 } 47 }
在vue文件中使用:
1 <template> 2 <view> 3 <text @tap="clickDebounce()">防抖</text> 4 <text @tap="clickThrottle()">节流</text> 5 </view> 6 </template> 7 8 <script> 9 import { debounce, throttle } from '@/utils/index.js' 10 export default { 11 data() { 12 return { 13 num: 0 14 } 15 }, 16 methods: { 17 // 防抖 18 clickDebounce: debounce(function() { 19 this.num += 1 20 console.log('第' + this.num +'次点击' ) 21 }, 600), 22 // 节流 23 clickThrottle: throttle(function() { 24 this.num += 1 25 console.log('第' + this.num +'次点击' ) 26 }, 800) 27 } 28 } 29 </script>
运行结果: