学习记录-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>
相关推荐
codeejun8 分钟前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
大连好光景19 分钟前
腾讯云 ADP 前沿部署工程师 (FDE) 学习笔记(二)
笔记·学习·agent开发平台·adp·实战练习
云草桑20 分钟前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
码途行者9 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员9 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇10 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu11 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu13 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
IT空门:门主13 小时前
LangChain4j 1.24.0 深度解读:新特性、版本对比与学习路线
java·学习
bai27313 小时前
path.join('C:\a', '\b') 给我 C:\a\b,path.resolve 给 C:\b:Windows 上 51 行路径实测
javascript·后端