debounce 周期内有新事件触发,清除旧定时器,重置新定时器;这种方法,需要高频的创建定时器。
throttling 周期内有新事件触发时,重置定时器开始时间撮,定时器执行时,判断开始时间撮,若开始时间撮被推后,重新设定延时定时器。
1.定义模块文件并导出防抖函数和节流函数
/** * 函数防抖 (只执行最后一次点击) * @param fn * @param delay * @returns {Function} * @constructor */ export const Debounce = (fn, t) => { let delay = t || 500; let timer; console.log(fn) console.log(typeof fn) return function () { let args = arguments; if(timer){ clearTimeout(timer); } timer = setTimeout(() => { timer = null; fn.apply(this, args); }, delay); } }; /** * 函数节流 * @param fn * @param interval * @returns {Function} * @constructor */ export const Throttle = (fn, t) => { let last; let timer; let interval = t || 500; return function () { let args = arguments; let now = +new Date(); if (last && now - last < interval) { clearTimeout(timer); timer = setTimeout(() => { last = now; fn.apply(this, args); }, interval); } else { last = now; fn.apply(this, args); } } };2.在组件中导入函数
import { Debounce, Throttle } from '@/common/config/debThr.js';3.methods中调用
... methods:{ /* 小提示:不要写成回调函数的形式 this指向改变了 */ getAliyunData:Throttle(function(){ ... },1000), } ...