节流&防抖

节流:wait时间内只能执行一次func

防抖:触发后延迟wait秒调用func

代码对比:(建议自己手敲一遍,不要养成直接cv的坏习惯)

节流:

节流&防抖_第1张图片

其中的apply函数是   

apply() 是 JavaScript 函数的一个方法,它用于调用函数并设置函数内部 this 关键字的指向。

throttle() 函数中,func 是传入的需要防抖的函数,args 是该函数的参数列表。当节流函数执行时,会通过 apply() 方法调用传入的函数,并将 this 指向当前的上下文环境,同时将参数 args 传递给该函数。 

节流函数通常运用在限制调用频率场景

  • 搜索框输入时的实时联想
  • 拖拽场景防止超高频次触发位置变动
  • 滚动场景监听scroll事件计算位置信息,比如判断是否到页面底部自动加载更多

防抖:

节流&防抖_第2张图片

防抖函数通常运用在限制调用次数场景

  • 文本输入的验证,连续输入后验证一次即可
  • 防止鼠标迅速点击多次提交按钮
  • 监听 resize 事件计算尺寸信息
//防抖
function debounce(func, wait) {
  let timer = null;

  return function () {
    //检查是否存在定时器
    if (timer) {
      //清除定时器
      clearInterval(timer);
      timer = null;
    }

    let self = this;
    let args = arguments;//args 是用户函数的参数列表

    timer = setTimeout(function () {
      func.apply(self, args);//执行用户函数
      timer = null;//重置定时器
    }, wait)
  }
}
//节流
//func是用户传入需要防抖的函数
//wait是等待时间
function throttle(func, wait=50) {
  let lastTime = 0;//上一次执行该函数的时间
  let timer = null;

  return function () {
    //如果存在定时器要先清除
    if (timer) {
      clearInterval(timer);
      timer = null;
    }

    let self = this;
    let args = arguments;
    let nowTime = +new Date();

    //剩余等待时间
    const remainWaitTime = wait - (nowTime - lastTime);

    if (remainWaitTime <= 0) {
      lastTime = nowTime;
      //apply() 是 JavaScript 函数的一个方法,它用于调用函数并设置函数内部 this 关键字的指向。
      func.apply(self, args);
    } else {
      //继续等待remainWaitTime再执行
      timer = setTimeout(function () {
        lastTime = +new Date();
        func.apply(self, args);
        timer = null;//重置定时器
      }, remainWaitTime)
    }
  }
}

你可能感兴趣的:(javascript,防抖,节流)