JavaScript——防抖与节流

JavaScript——防抖与节流

一、防抖(debounce)

1.1 概念

防抖:单位时间内,频繁触发事件,只执行最后一次。

举个栗子:在王者荣耀游戏内频繁按回城键,每一次按下回城键都会打断上一次回城,并且重新开始回城。

使用场景:

  1. 搜索框搜索输入:只需用户最后一次输入完,再发送请求,而不是输入一个字就发送一次请求。
  2. 手机号、邮箱验证输入检测:输完再自动验证。

实现防抖的两种方式:

  1. 使用工具库lodash中的_.debounce()方法
  2. 手写防抖函数

下面我们分别使用这两种方法优化以下需求的实现:

鼠标每移动一次,盒子内的数值加一。(防抖间隔设置为500毫秒)

1.2 lodash中的_.debounce()实现防抖

<!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>防抖</title>
    <script src="./node_modules/lodash/lodash.js"></script>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: pink;
            text-align: center;
            line-height: 300px;
            font-size: 40px;
            font-weight: 900;
            color: aliceblue;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        const box = document.querySelector('.box')
        // console.log(box);
        function mouseMove() {
            box.innerHTML = num++
        }
        let num = 0
        box.addEventListener('mousemove', _.debounce(mouseMove, 500))
    </script>
</body>

</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mTis2jns-1679899257825)(D:\Study Files\前端\Gif\防抖.gif)]

该方法的详细使用可参考文档: JavaScript 实用工具库——lodash中文文档

1.3. 手写防抖函数

核心:利用 setTimeout 定时器实现

  1. 声明定时器变量

  2. 每次鼠标移动(事件触发)的时候都要先判断是否有定时器,如果有先清除以前的定时器

  3. 如果没有定时器,则开启定时器,存入到定时器变量里面

  4. 定时器里面写函数调用

let num = 0
const box = document.querySelector('.box')
function mouseMove() {
    box.innerHTML = num++
}
function debounce(fn, t) {
    let timer
    return function () {  // 返回匿名函数
        if (timer) clearTimeout(timer)
        timer = setTimeout(function () {
            fn()  // 加小括号调用函数
        }, t)
    }
}
box.addEventListener('mousemove', debounce(mouseMove, 500))

能够实现和lodash中的_.debounce()一样的效果。

1.4. Vue中手写防抖函数传参版

utils/debounce.js

// 防抖
export const debounce = function (fn, wait = 500) {
  // console.log(...arguments);  // fn wait
  // 这个timer只会在页面初始化的时候定义一次,后面每一次输入都直接触发return的函数
  let timer;
  // console.log(this);  // undefined
  return function () {
    // console.log(arguments); // e str
    // console.log(this); // VueComponent  因为返回匿名返回后相当于在组件直接调这个函数
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      // console.log(this);  // VueComponent
      // apply改变此函数this指向并向此函数传递参数
      fn.apply(this, arguments);
    }, wait);
  };
};

.vue

<template>
    <div>
        <input v-model="inputValue" @input="(e) => watchInput(e, 'Nihao')">
    </div>
</template>

<script>
import { debounce } from '../utils/debounce.js'

export default {
    data() {
        return {
            inputValue: '',
        }
    },
    methods: {
        watchInput: debounce((e, str) => {
            // console.log(this);  // undefined 如果不用箭头函数就是VC
            console.log(e.target.value);
            console.log(str);
        }, 2000),
    },
}
</script>

效果展示:
在这里插入图片描述

二、节流(throttle)

2.1 概念

节流:单位时间内,频繁触发事件,只执行第一次。

举个栗子:王者荣耀技能有一定cd,点击释放技能后,cd期间无法继续释放技能。

使用场景:

高频事件:鼠标移动mousemove、页面尺寸缩放resize、滚动条滚动scroll等等。

实现防抖的两种方式:

  1. 使用工具库lodash中的_.throttle()方法
  2. 手写节流函数

下面我们分别使用这两种方法优化以下需求的实现:

鼠标在盒子上移动,不管移动多少次,每隔2000毫秒才+1。

2.2 lodash中的_.throttle()实现节流

const box = document.querySelector('.box')
function mouseMove() {
    box.innerHTML = num++
}
let num = 0
box.addEventListener('mousemove', _.throttle(mouseMove, 2000))

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Kn2PSAt2-1679899257826)(D:\Study Files\前端\Gif\节流.gif)]

2.3 手写节流函数

节流的核心就是利用定时器来实现:

  1. 声明一个定时器变量
  2. 当鼠标每次滑动都先判断是否有定时器,如果有定时器则不开启新定时器
  3. 如果没有定时器则开启定时器,记得存到变量里面

注意:1.定时器里面调用执行的函数 2.定时器里面要把定时器清空。

let num = 0
        const box = document.querySelector('.box')
        function mouseMove() {
            box.innerHTML = num++
        }
        function throttle(fn, t) {
            let timer = null
            return function () {  // 返回匿名函数
                if (!timer) {
                    timer = setTimeout(function () {
                        fn()  // 加小括号调用函数
                        timer = null  // 清空定时器
                    }, t)
                } else {
                    return
                }
            }
        }
        box.addEventListener('mousemove', throttle(mouseMove, 2000))

能够实现和lodash中的_.throttle()一样的效果。

值得注意的是:

定时器里面清空定时器只能将定时器置空,不能使用clearTimeout(定时器变量名),因为定时器还在运作,无法使用clearTimeout(定时器变量名)

2.4 Vue中手写节流函数传参版

和防抖同理

// 节流
export const throttle = function (fn, wait = 500) {
    let timer = null
    return function () {
        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(this, arguments);
                timer = null
            }, wait)
        } else {
            return
        }
    }
}

三、总结

性能优化说明使用场景
防抖单位时间内,频繁触发事件,只执行最后一次搜索框搜索输入、手机号、邮箱验证输入检测
节流单位时间内,频繁触发事件,只执行第一次高频事件:鼠标移动mousemove、页面尺寸缩放resize、滚动条滚动scroll等等
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值