防抖和节流

126 阅读1分钟

防抖

防抖:通过setTimeOut方式,在一定时间段内,多次触发=>1次触发

//防抖函数 debounce
function debounce(func, wait) {
  let timer = null;

  // 将debouce处理结果当作函数返回
  return function() {
    let context = this;  //改变函数内部的this
    let args = arguments; // event指向问题
    if(timer) {
      clearTimeout(timer)
    }
    timer =  setTimeout(() => {
      func.apply(context, args);
    }, wait)
    
  }
}

怎么写出来呢?

//写基本 结构 返回一个function 和 使用定时器
// 再解决 this指向问题,和event问题
function debounce(func, wait){
    let timer = null
    return function(){
        let context = this;
        let args = arguments;
        if(timer) clearTimeout(timer)
        timer = setTimeout(() => {
            func.apply(context, args);
        }, wait)
    }
}

节流

节流的概念,节流是将多次执行变成每隔一段时间执行

//节流函数
function throttle(func, wait) {
  let begin = 0;
  return function() {
    let context = this;
    let args = arguments;
    let cur = new Date().getTime(); //毫秒时间戳
    if(cur - begin > wait){
      func.apply(context, arguments)
      begin = cur;
    }
  }
}