自学内容网 自学内容网

学习记录-js进阶-性能优化

性能优化分类

防抖和节流

实现效果

防抖
在这里插入图片描述
节流
在这里插入图片描述

性能优化实现步骤

1. 准备阶段

理解防抖节流的概念以及基本的实现方法

  1. 防抖:在事件执行过程中,如果被打断,则重新开始计时,只执行最后一次。一般用于鼠标移动事件,页面滚动事件等高频率触发事件
  2. 节流:在事件执行过程中,如果重复执行,则不中断,直到本次事件执行完毕后,在执行下一次事件,同样用于高频率触发事件

2. 防抖函数

判断是否有定时器,如果有则清除定时器,如果没有则启动计时器

  1. 函数传入两个参数,第一个为执行函数,第二个为执行时间
  2. 函数体要写到return中回调,使之重复执行
function debounce(fun, t) {
    let timer
    return function () {
      if (timer) clearTimeout(timer)//如果存在定时器,则清除定时器
      timer = setTimeout(() => {
        fun()
      }, t)
    }
  }

3. 节流函数

判断是否有定时器,只有当不存在定时器的时候,启动计时器

  1. 定时器的返回值为数字
  2. 一般情况下,定时器内部无法清除定时器,所以要使用timer=null的方式来清除定时器
function throttle(fun, t) {
    let timer = null
    return function () {
      if (!timer) {
        timer = setTimeout(() => {
          fun()
          timer = null//使用timer=null清除定时器
        }, 1000)
      }
    }
  }

4. 调用函数

function fn1() {//定义执行函数
    console.log(111111111)
  }
  document.querySelector('.box').addEventListener('mousemove', throttle(fn1, 1000))//调用性能优化函数

完整实例代码

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      height: 400px;
      width: 400px;
      background-color: black;
      margin: 200px 100px;
    }
  </style>
</head>

<body>
  <div class="box">

  </div>
</body>

</html>
<script>
  function fn1() {
    console.log(111111111)
  }
  document.querySelector('.box').addEventListener('mousemove', throttle(fn1, 1000))
  // 防抖
  function debounce(fun, t) {
    let timer
    return function () {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        fun()
      }, t)
    }
  }
  // 节流
  function throttle(fun, t) {
    let timer = null
    return function () {
      if (!timer) {
        timer = setTimeout(() => {
          fun()
          timer = null
        }, 1000)
      }
    }
  }
</script>

原文地址:https://blog.csdn.net/sinbowper/article/details/146382613

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!