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