节流,防抖函数实现

355 阅读1分钟

防抖函数

   function debounce(func, time) {
    let timer = null;
    return function () {
      let context = this
      // console.log('context :', this);
      clearTimeout(timer)
      timer = setTimeout(function () {
        console.log('this :', this);
        func.call(this)
      }, time)
    }
  }

节流函数

    function throttle(method, time) {
    var timer = null;
    var startTime = 0;
    return function () {
      var endTime = new Date();
      var resTime = endTime - startTime;
      //判断大于等于我们给的时间采取执行函数;
      if (resTime >= time) {
        method.call(this);
        //执行完函数之后重置初始时间,等于最后一次触发的时间
        startTime = endTime;
      }
    }
  }

测试:

  window.onscroll = debounce(() => {
    console.log(1);
  }, 500)



  function fn() {
    _throttle()
  }
  let _throttle = throttle(function () {
    console.log(2);
  }, 1000)
  window.onmousemove = fn