函數防抖(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>
運行結果: