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

目录

性能优化分类

防抖和节流

实现效果

防抖

节流

性能优化实现步骤

1. 准备阶段

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

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

2. 防抖函数

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

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

3. 节流函数

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

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

4. 调用函数

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

完整实例代码

javascript 复制代码
<!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>
相关推荐
wearegogog1237 小时前
C#与Twincat 2 实现上位机控制软PLC功能
开发语言·c#
DisonTangor7 小时前
【阿里拥抱开源】Qwen团队开源新一代深度思考模型——Qwen3-Next-80B-A3B-Thinking
人工智能·学习·语言模型·开源·aigc
wow_DG7 小时前
【Vue2 ✨】Vue2 入门之旅 · 进阶篇(九):Vue2 性能优化
javascript·vue.js·性能优化
军训猫猫头8 小时前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
MuMuMu#8 小时前
Spring Cloud Gateway基础复习
java·运维·学习
Eiceblue8 小时前
使用 C# 设置 Excel 单元格格式
开发语言·后端·c#·.net·excel
GDAL8 小时前
Knockout-ES5 入门教程
javascript·knockout
正义的大古8 小时前
OpenLayers数据源集成 -- 章节八:天地图集成详解
开发语言·javascript·ecmascript·openlayers
LDM>W<8 小时前
Electron下载失败
前端·javascript·electron
EndingCoder8 小时前
Electron 新特性:2025 版本更新解读
前端·javascript·缓存·electron·前端框架·node.js·桌面端