1.debounce去抖動
function debounce(method,delay){ var timer = null; return function(){ var context = this,args = arguments; clearTimeout(timer); timer = setTimeout(function(){ method.apply(context,args); },delay); } }
// 防抖函數 const debounce = (fn, delay) => { let timer = null; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; };
2.throttle節流
function throttle(method, delay, time) { var timeout,startTime = +new Date(); return function() { var context = this, args = arguments, curTime = +new Date(); clearTimeout(timeout); // 如果達到了規定的觸發時間間隔,觸發 handler if (curTime - startTime >= time) { method.apply(context, args); startTime = curTime; } else { // 沒達到觸發間隔,重新設定定時器 timeout = setTimeout(method, delay); } };
// 節流函數 const throttle = (fn, delay = 500) => { let flag = true; return (...args) => { if (!flag) return; flag = false; setTimeout(() => { fn.apply(this, args); flag = true; }, delay); }; };