高阶函数

185 阅读1分钟

1、函数节流

// 函数节流 (减少对应的处理开销,让处理方法的执行频率减少)
function throttle(fn, wait) {
  let timer = null;
  let lastTime = null;
  return function() {
    let context = this;
    let now = new Date();
    // 上次执行时间和这次触发时间大于一个执行周期,就执行
    if (now - lastTime > wait) {
      // 之前有定时器就清除
      if (timer) {
        clearTimeout(timer)
        timer = null;
      }
      lastTime = now;
      fn.apply(context, arguments);
    } else if (!timer) {
      timer = setTimeout(() => {
        fn.apply(context, arguments);
      }, wait)
    }
  }
}

2、函数防抖动

// 函数防抖动 (去掉中间的执行函数,只执行最后一次事件)
function debounce(fn, wait) {
  let timer = null;
  let lastTime = null;
  return function() {
    let context = this;
    let now = new Date();
    return function() {
      // 判断是不是抖动
      if (now - lastTime > wait) {
        timer = setTimeout(() => {
          fn.apply(context, arguments);
        }, wait);
      } else {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(() => {
          fn.apply(context, arguments);
        }, wait);
      }
      lastTime = now;
    }
  }
}

3、分时函数

// 分时函数(短时间插入大量的dom节点,会让浏览器吃不消,分批插入)
/**
* 分时函数
* @param {*创建节点需要的数据} list 
* @param {*创建节点逻辑函数} fn 
* @param {*每一批节点的数量} count
*/

const timeCount = function(list,fn,count = 1) {
  let insert, // 插入数据
      timer = null; // 计时器
  const start = function() {
    for (let i=0;i<Math.min(count, list.length);i++) {
      insert = list.shift();
      fn(insert);
    }
  }
  return function() {
    timer = setInterval(() => {
      if (list.length === 0) {
        clearInterval(timer);
        timer = null;
        return;
      }
      start();
    }, 2000);
  }
}
// 分流调用
const arr = [];
for (let i=0;i<100;i++) {
    arr.push(i);
}
const renderList = timeCount(arr, function(data) {
  const div = document.createElement('div');
  div.innerHTML = data + 1;
  document.body.appendChild(div);
}, 20);

renderList();

4、惰性函数

// 惰性加载函数
// 1、在加载之前进行一次嗅探,但是放在公共库中不使用,就多余了。
const addEventOptimization = (function() {
  if (window.addEventListener) {
    return (el, type, handler) => {
      el.addEventListener(type, handler, false)
    }
  }
  // for ie
  if (window.attachEvent) {
    return (el, type, handler) => {
      el.attachEvent(`on${type}`, handler)
    }
  }
})();

// 开始进入分支,函数内部修改函数的实现。下次进入不存在分支
// 惰性加载函数
let addEventLazy = function(el, type, handler) {
 if (window.addEventListener) {
   // 一旦进入分支,便在函数内部修改函数的实现
   addEventLazy = function(el, type, handler) {
     el.addEventListener(type, handler, false)
   }
 } else if (window.attachEvent) {
   addEventLazy = function(el, type, handler) {
     el.attachEvent(`on${type}`, handler)
   }
 }
 addEventLazy(el, type, handler)
}
addEventLazy(document.getElementById('eventLazy'), 'click', function() {
 console.log('lazy ')
})