首页 > 技术文章 > js 函数防抖和节流

lilei-site 2019-12-13 15:24 原文

一、防抖

函数防抖和节流,比如像滚动条触发事件的时候,短时间内触发的事件太多,并没有意义,所以可以减少触发的事件,来节省

内存的消耗,更能使页面更加流畅

function debounce(fn, delay) {
  let timer = null;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  }
}

 

二、节流

节流和防抖的功能差不多,实现机制相差不大,看一下代码就可以了

function throttle(fn, cycle) {
  let start = Date.now();
  let now;
  let timer;
  return function () {
    now = Date.now();
    clearTimeout(timer);
    if (now - start >= cycle) {
      fn.apply(this, arguments);
      start = now;
    } else {
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, cycle);
    }
  }

  

推荐阅读