JS實現函數節流方法


函數節流可以一定程度得減少系統的損耗,方法如下:

/**
 * 函數節流方法
 * @param {Function} fn 需要進行節流執行的函數
 * @param {Number} delay 延時執行的時間
 * @param {Number} atleast 至少多長時間觸發一次
 * @return {Function} 返回節流執行的函數
 */
function throttle (fn, delay, atleast = 0) {
  let timer = null; //定時器
  let previous = 0; //記錄上一次執行的時間
  
  return (...args) => {
    let now = +new Date();   //當前時間戳
    if (!previous) previous = now; // 賦值開始時間
    
    if (atleast && (now - previous) > atleast) {
      fn.apply(this, args);  //文章下面有給出該行代碼的理解
      // 重置上一次開始時間為本次結束時間
      previous = now;
      timer && clearTimeout(timer);
    } else {
      timer && clearTimeout(timer); // 清除上次定時器
      timer = setTimeout(() => {
        fn.apply(this, args);
        console.log('else')
        previous = 0;
      }, delay);
    }
  }
}

 

其中 fn.apply(this,  args) 不難理解,我們通過一段代碼來看:

  function person(name) {
    this.name = name;
    this.sayname = function() {
      alert(this.name)
    }
  }
  
  function student(name) {
    person.apply(this, arguments)
  }

  var studenta = new student('xiaoming')
  studenta.sayname();
此時,屏幕會出現 alert('xiaoming')的效果。

由此可見 fn.apply(this,  args) 實現了對 fn 的繼承, args 需要是數組形式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM