防抖(debounce)和节流(throttle)是前端开发中常用的性能优化技术,用于控制函数的执行频率。

一、防抖与节流

Test
导读目录

1
防抖(debounce) 
防抖应用场景 
非立即执行版 
立即执行版本 
合成版本 防抖 

节流

节流应用场景 
时间戳版本 
定时器版本 

总结

1
#### 1防抖(debounce) 
防抖应用场景
非立即执行版
1
/** * @description:  * @param {*} func 触发的时间 * @param {*} wait 多少时长才执行事件 * @return {*} */        function debounce(func, wait) {            let timeout;            return function(){                // 获取当前作用域和参数                const context = this;                const args = [...arguments]                 // 如果当前timeout 存在                // 清空定时器,再次等待wait时间过后再次执行事件                if(timeout) clearTimeout(timeout)                // 定时执行 传递进来的事件                timeout = setTimeout(()=>{                    func.apply(context,args)                },wait)              }        }
立即执行版本
1
function func,wait) {  let timeout;  return function () {      const context = this;      const args = [...arguments];      if (timeout) clearTimeout(timeout);      const callNow = !timeout;      timeout = setTimeout(() => {          timeout = null;      }, wait)      if (callNow) func.apply(context, args)  }}
1
2
3
4
5
6


##### 合成版本 防抖


/** * @desc 函数防抖 * @param func 函数 * @param wait 延迟执行毫秒数 * @param immediate true 表立即执行,false 表非立即执行 */function debounce(func, wait, immediate) {  let timeout;  return function () {    const context = this;    const args = [...arguments];    if (timeout) clearTimeout(timeout);    if (immediate) {      const callNow = !timeout;      timeout = setTimeout(() => {        timeout = null;      }, wait)      if (callNow) func.apply(context, args)    }    else {      timeout = setTimeout(() => {        func.apply(context, args)      }, wait);    }  }}

2节流

节流应用场景
时间戳版本
1
function func, wait) {    var previous = 0;    return function() {        let now = Date.now();        let context = this;        let args = arguments;        if (now - previous > wait) {            func.apply(context, args);            previous = now;        }    }}
1
2
3
4
5
6
  

##### 定时器版本

function func, wait) {    let timeout;    return function() {        let context = this;        let args = arguments;        if (!timeout) {            timeout = setTimeout(() => {                timeout = null;                func.apply(context, args)            }, wait)        }    }}

3总结

https://github.com/mqyqingfeng/Blog/issues/26

React Hook | 必 学 的 9 个 钩子
Vue权限路由思考
Vue 组件通信的 8 种方式
MYSQL常用操作指令

 TypeScript学习指南(有PDF小书+思维导图) 

本文标题: 浅聊防抖与节流 实现与应用

发布时间: 2019年03月10日 00:00

最后更新: 2025年12月30日 08:54

原始链接: https://haoxiang.eu.org/c9dc68c3/

版权声明: 本文著作权归作者所有,均采用CC BY-NC-SA 4.0许可协议,转载请注明出处!

× 喜欢就赞赏一下呗!
打赏二维码