美文网首页
防抖和节流

防抖和节流

作者: vivianXIa | 来源:发表于2021-10-15 15:34 被阅读0次

优化高频率事件onscroll oninput onkeyup keydown... 降低代码执行评率

1: 页面展示过程

image
  • javaScript动画/往页面里添加一些DOM

  • Style确定每个DOM应该用什么的样式

  • Layout布局,计算最终显示的位置和大小

  • Paint绘制dom,在不同的层上绘制

  • Composite渲染层合同

用户scroll和resize行为会导致页面不断重新渲染,如果在绑定的回调函数中大量操作dom也会出现页面卡顿

  • 优化方案:防抖和节流
image image

2:函数节流(Throttle)

节流就是保证一段时间内,核心代码执行一次

打个比方:水滴积攒到一定重量才会下落

简单写法

function throttle(fun,wait){
  let previous = 0;
  let now = new Date();
  if(now-previous>wait){
    fun.bind(this,arguments);
    previous = now;
   }
}

复杂写法(考虑开始 结束是否执行)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="btn" style="background: red;color: #FFF;display: inline-block;padding: 10px;">点击节流</button>
  <script>
    // 但是最后一次点击不会执行 我期望最后一次也能执行
    function throttle(func, wait, options)
    {
      let args, context, previous = 0, timeout;
      let throttled = function (params)
      {
        args = arguments;
        context = this;
        let now = new Date();
        if(!previous&&options.leading){previous=now}
        let remaining = wait - (now - previous);
        if (remaining <= 0) {
          if (timeout) {
            clearTimeout(timeout)
            timeout = null
          }
          func.apply(this, arguments);
          previous = now;
        } else if (!timeout) {
          timeout = setTimeout(() =>
          {
            previous = options.leading?0:now
            func.apply(this, arguments);
          }, remaining);
        }
      }
      return throttled
    }

    function logger()
    {
      console.log('点击点击点击');
    }
    //trailing 点击最后一次需要执行 leading刚开始第一次点击也要等待
    btn.addEventListener('click', throttle(logger, 1000, { trailing: true,leading:true }));
  </script>
</body>

</html>

3:防抖(Debounce)

防抖就是一段事件结束后,才能触发一次事件,如果一段事件未结束再次触发事件,就会重新开始计算

打个比方:你在电梯里,门快要关了,突然有人准备上来。电梯并没有改变楼层。而是再次打开电梯门。电梯延迟了改变楼层的功能,但是优化了资源

简单实现

function debounce(func, wait,immediate)
    {
      let timer;
      return function ()
      {
        clearTimeout(timer)
        timer = setTimeout(() =>
        {
          func.apply(this,arguments);
        }, wait);
      }
    }

首次点击也要执行一次

    {
      let timer;
      return function ()
      {
        if (!timer&&immediate) {
          func.apply(this, arguments);
        }
        clearTimeout(timer)
        timer = setTimeout(() =>
        {
          console.log('执行');
          func.apply(this, arguments);
          timer=null
        }, wait);
      }
    }

    function logger()
    {
      console.log('logger点击点击点击');
    }
    //第三个参数表示首次触发
    btn.addEventListener('click', debounce(logger, 1000, true))

4. 两者合并:防抖+节流

非常复杂,建议掌握上边的代码先

参考库:lodash lodash/throttle

image image

防抖

//debounce 先开一个定时器 只要一直点击 到时间什么都不做 就再开一个定时器
function debounce(fun,wait,opts={}) {
  let leading = true;//第一次点击时触发
  let trailing = true;//最后一次也要触发
  //loadash 定时器实现的
  let lastCallTime;//最后调用的时间 previous
  let timeout;
  let lastThis;//返回函数的this
  let lastArgs;//返回函数的参数

  //shouldInvoke 是否应该调用
  let shouldInvoke = function (now) {
    let sinceLastTime = now - lastCallTime
    //true 第一次
    return lastCallTime === undefined || sinceLastTime > wait
  }
  //leadingEdge 是否第一次执行
  let invokeFunc = function (time) {
    fun.apply(lastThis,lastArgs)
  }
  //startTimer就是开启一个定时器
  let startTimer = function (timeExpierd,wait) {
    timeout = setTimeout(timeExpierd,wait)
  }
  let remainingWait = function (now) {
    return wait - (now - lastCallTime)
  }
  let trailingEdge = function () {
    timeout = undefined
    if(trailing){
      invokeFunc(time)
    }
  }
  let timeExpired = function () {
    let now = Dae.now();
    if(shouldInvoke(now)){//
      //触发结束的方法
      return trailingEdge(now);
    }
    startTimer(timeExpired,remainingWait(now))
  }
  let leadingEdge = function (time) {
    if(leading){//需要执行就调用函数
      invokeFunc(time)
    }
    startTimer(timeExpierd,wait);//开启一个定时器,看下一次定时器到了,是够需要执行
  }
  let debounced = function(){
    lastThis = this;
    lastArgs  =args;
    let now = Date.now();
    //判断当前的debounce是够需要执行
    let isInvoking = shouldInvoke(now)
    lastCallTime = now;
    if(isInvoking){
      if(timeout==undefined){
        leadingEdge(now);
      }
    }
  }
  return debounced
}

防抖+节流

function debounce(fun,wait,opts={}) {
  let maxWait;
  if('maxWait' in opts){
    maxWait = opts.maxWait
  }
  let leading = true;//第一次点击时触发
  let trailing = true;//最后一次也要触发
  //loadash 定时器实现的
  let lastCallTime;//最后调用的时间 previous
  let timeout;
  let lastThis;//返回函数的this
  let lastArgs;//返回函数的参数

  let lastInvokeTime;
  //shouldInvoke 是否应该调用
  let shouldInvoke = function (now) {
    let sinceLastTime = now - lastCallTime;
    let sinceLastInvoke = now - lastInvokeTime;
    //true 第一次
    return lastCallTime === undefined || sinceLastTime > wait ||sinceLastInvoke>=wait
  }
  //leadingEdge 是否第一次执行
  let invokeFunc = function (time) {
    lastInvokeTime = time
    fun.apply(lastThis,lastArgs)
  }
  //startTimer就是开启一个定时器
  let startTimer = function (timeExpierd,wait) {
    timeout = setTimeout(timeExpierd,wait)
  }
  let remainingWait = function (now) {
    return wait - (now - lastCallTime)
  }
  let trailingEdge = function () {
    timeout = undefined
    if(trailing){
      invokeFunc(time)
    }
  }
  let timeExpired = function () {
    let now = Dae.now();
    if(shouldInvoke(now)){//
      //触发结束的方法
      return trailingEdge(now);
    }
    startTimer(timeExpired,remainingWait(now))
  }
  let leadingEdge = function (time) {
    if(leading){//需要执行就调用函数
      invokeFunc(time)
    }
    startTimer(timeExpierd,wait);//开启一个定时器,看下一次定时器到了,是够需要执行
  }
  let debounced = function(){
    lastThis = this;
    lastArgs  =args;
    let now = Date.now();
    //判断当前的debounce是够需要执行
    let isInvoking = shouldInvoke(now)
    lastCallTime = now;
    if(isInvoking){
      if(timeout==undefined){
        leadingEdge(now);
      }
    }
  }
  return debounced
}


function throttle(func,wait) {
  return debounce(func,wait,{
    maxWait:true
  })
}

5. requestAnimationFrame

编写动画循环的关键是要知道延迟时间多长时间合适,如果时间过长会导致动画不流畅,时间果断会造成过度的绘制。requestAmimationFrame采用系统时间间隔,保持最佳绘制效率

此方法是用来咋页面绘制之前,通知浏览器调用一个指定的函数,被调用的频率约是每秒60次,在运行浏览器会自动优化方法的调用

lodash方法中,如果wait=0,会采用requestAnimationFrame进行哟花

image

相关文章

  • 谈谈js中的节流和防抖函数

    关于节流和防抖,这篇文章说的很好了,深入lodash源码分析防抖和节流深入篇 | Lodash 防抖和节流是怎么实...

  • JavaScript防抖和节流

    1. 认识防抖和节流 1.1. 对防抖和节流的认识 防抖和节流的概念其实最早并不是出现在软件工程中,防抖是出现在电...

  • 前端性能优化-浅谈js防抖和节流

    浅谈js防抖和节流

  • Javascript 基础

    1、函数防抖和函数节流 【《javascript高级程序设计》里,函数节流是这里讲的函数防抖。】函数防抖: 在事件...

  • js 防抖 节流

    节流 防抖1 防抖2

  • 2019-03-27

    js的防抖和节流 据我所知防抖和节流都是为了优化作用,减轻浏览器和服务端的负担,防抖和节流俩个的英文要记住: de...

  • js的防抖和节流

    js的 防抖(debounce)和 节流(throttle ) 防抖和节流一般用于高频触发事件,属于浏览器性能优化...

  • 手写防抖和节流函数实现

    1. 认识防抖和节流函数 防抖和节流的概念其实最早并不是出现在软件工程中,防抖是出现在电子元件中,节流出现在流体流...

  • 实现防抖和节流

    一、认识防抖和节流函数 防抖和节流的概念其实最早并不是出现在软件工程中,防抖是出现在电子元件中,节流出现在流体流动...

  • 2019-04-24关于节流和防抖

    节流: 应用场景: 防抖: 应用场景: 1.节流 2.防抖

网友评论

      本文标题:防抖和节流

      本文链接:https://www.haomeiwen.com/subject/dpemoltx.html