input值变化,延时触发事件(防抖,节流)
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); }; };