节流和防抖

一、什么是防抖(debounce)

原理:事情触发后,等待一段时间再执行回调,如果在这段时间内再次触发,则重新计时

应用场景:

1、输入框实时搜索

2、窗口大小调整resize

3、防止表单重复提交

二、什么是节流(throttle)

原理:在一定时间间隔内,只执行一次回调函数,不管事件触发了多少次

应用场景:

1、页面滚动事件scroll(比如监听页面滚动到底部加载下一页)

2、按钮频繁点击事件(防止重复提交)

3、鼠标异动mousemove

实现原理与代码

防抖实现

原理:每次事情触发时,清除上一个定时器并重新设置新的定时器,直到时间停止触发后延迟delay毫秒执行

手写防抖函数(不依赖Lodash)

 1 function debounce(fn, delay) {
 2   let timer = null
 3   return function (...args) {
 4     if (timer) {
 5       clearTimeout(timer)
 6     }
 7     timer = setTimeout(() => {
 8       fn.apply(this, args)
 9     }, delay)
10   }
11 }

在vue中使用手写防抖函数

可以将debounce函数定义在methods或者单独放在一个utils.js文件中,在组件中引用并使用它

html

1 <el-input v-model="keyword" @input="debouncedSearch" placeholder="请输入关键词搜索"></el-input>

js

 1 export default {
 2   methods: {
 3     // 手写防抖函数
 4     debounce(fn, delay) {
 5       let timer = null;
 6       return function (...args) {
 7         if (timer) clearTimeout(timer);
 8         timer = setTimeout(() => {
 9           fn.apply(this, args);
10         }, delay);
11       };
12     },
13     // 搜索方法
14     searchKeywordHandler() {
15       this.currentTableType = 'search';
16       this.searchByKeyword();
17     },
18     mounted() {
19       // 使用 debounce 包裹搜索方法
20       this.debouncedSearch = this.debounce(this.searchKeywordHandler, 300);
21     }
22   }
23 }

如果保留lodash/debounce

1 import debounce from 'lodash/debounce'
1 methods: {
2   searchKeyword: debounce(function () {
3     this.currentTableType = 'search'
4     this.searchByKeyword()
5   }, 300)
6 }

节流实现

原理:记录上一次执行时间,比较当前时间与上一次的时间差,只有达到delay时才执行

 1 function throttle(fn, delay) {
 2     let lastTime = 0
 3     return function (...args) {
 4         let nowTime = Date().now()
 5         if (nowTime - lastTime >= delay) {
 6             fn.apply(this, args)
 7             lastTime = nowTime
 8         }
 9     }
10 }        

如果保留lodash/throttle

1 import throttle from 'lodash/throttle'
 1 handleCopy: throttle(function (row, $index) {
 2   this.markContactUsed(row.id)
 3   let refsName = 'myPopover_' + row.id + '_' + $index
 4   if (this.$refs[refsName]) {
 5     this.$refs[refsName].hide()
 6   }
 7 }, 3000, {
 8   leading: true,
 9   trailing: false
10 }),

防抖VS节流

特性 防抖 节流
执行时机 事件停止触发后执行 固定时间间隔执行
重置计时 每次触发都会重置计时 不会重置计时
适用场景 搜索框输入、rasize事件 滚动加载、按钮防重复点击、拖拽
极端情况 高频触发可能导致用不执行 高频触发会均匀执行
概括 多次触发—>最后一次有效 多次触发—>固定周期只执行一次
posted @ 2025-05-29 16:30  借晚风叙旧  阅读(72)  评论(0)    收藏  举报