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);
  };
};

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM