防抖Vs节流

  • 防抖动(停止触发时间超过设定的等待时间,再触发,第一次需要立即触发)
// 将会包装事件的 debounce 函数
function debounce(fn, delay, immediate) {
  // 维护一个 timer
  let timer = null;
    
  return function() {
    // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量
    let context = this;
    let args = arguments;
    if(immediate) {
        var callNow = !timer;
        if(callNow) {
            fn.apply(context, args);
        }
    }
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  }
}
  • 节流(长时间频繁触发,只在设定的时间点规律性的触发一次。并且保留最后一次的操作,第一次操作照样延迟触发)
 function throttle(fn, wait, options) {
      var previous = 0;
      var later = function() {
        fn.apply(this, arguments);
        previous = options.leading === false ? 0 : Date.now();
      }
      return function() {
        var now = Date.now();
        let context = this;
    	let args = arguments;
        if(!previous && options.leading === false) {
          previous = now;
        }
        var remaining = wait - (now - previous);
        if(remaining <= 0) { //连续点和第一次点的情况
          if(timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          fn.apply(context, args);
          previous = now;
        } else if(!timeout && options.trailing){ // 确保执行最后一次
          timeout = setTimeout(later, remaining);
        }
      }
    }

你可能感兴趣的:(前端技术知识)