js代码-防抖函数(立即执行和非立即执行)

本文介绍了JavaScript中的防抖(debounce)技术,通过两种实现方式展示了防抖函数的使用,一种是立即执行,另一种是非立即执行。防抖技术常用于限制函数的高频触发,例如在页面滚动事件或按钮点击事件中,有效提升性能。
防抖
即执行
 function debounce(fn, delay) {
   let timeid=null, flag = true;
   return function () {
     clearTimeout(timeid);
     if (flag) {
       fn();
       flag = false;
     } else {
       timeid = setTimeout(function () {
         flag = true;
       }, delay);
     }
   }
 }
 document.getElementById("myBtn").addEventListener("click", debounce(() => {
   console.log('调用成功');
 }, 3000));
//非立即执行
function debounce(fn, delay) {
  let timeid = null;
  return function () {
    if (timeid) {
      clearTimeout(timeid);
    }
    timeid = setTimeout(fn, delay);
  }
}
document.getElementById("myBtn").addEventListener("click", debounce(() => {
  console.log('调用成功');
}, 2000));
防抖(Debounce)是一种常见的函数优化技术,用于控制某个函数在一段时间内只执行一次,避免频繁触发(如窗口滚动、输入框输入、按钮重复点击等场景)。你提到的“加立即执行区域”可以理解为: - **立即执行**:在防抖开始时立刻执行函数一次,后续在冷却期内执行,直到冷却期结束后才能再次触发。 - **区域**:可能指作用域(`this` 指向)或事件绑定的特定 DOM 区域。我们这里理解为需要保留函数调用时的 `this` 参数,并可绑定到某个 DOM 元素上。 --- ### ✅ 实现一个支持「立即执行「保留 this 及参数」的 JavaScript 防抖函数 ```javascript /** * 防抖函数(支持立即执行 + 保留 this 参数) * @param {Function} func -防抖函数 * @param {number} wait - 等待时间(毫秒) * @param {boolean} immediate - 是否立即执行 * @returns {Function} - 包装后的防抖函数 */ function debounce(func, wait, immediate = false) { let timeout; return function executedFunction(...args) { const context = this; const later = () => { timeout = null; if (!immediate) { func.apply(context, args); } }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } ``` --- ### 🔍 解释代码逻辑 1. **闭包变量 `timeout`**: - 用于保存 `setTimeout` 的句柄,实现延迟清除重置。 2. **返回函数 `executedFunction`**: - 接收任意参数 `...args`,并保留调用上下文 `this`。 3. **`later` 函数**: - 延迟执行的逻辑。如果立即执行模式,则在此调用原函数。 4. **`callNow` 判断**: - 当 `immediate` 为 `true` 且当前没有定时器(即首次触发),就立即执行函数5. **`clearTimeout(timeout)`**: - 每次触发时清除之前的定时器,实现“重新计时”。 6. **`func.apply(context, args)`**: - 正确绑定 `this` 参数,适用于事件监听器等场景。 --- ### 🧪 使用示例:绑定到输入框事件(立即执行) ```html <input type="text" id="searchInput" placeholder="输入内容..." /> ``` ```javascript const input = document.getElementById('searchInput'); const handleInput = debounce(function (e) { console.log('当前输入值:', e.target.value); console.log('this 指向:', this); // 会正确指向 input 元素 }, 300, true); // 设置为立即执行 input.addEventListener('input', handleInput); ``` > 这样用户一输入就会立刻打印,但如果连续输入,则会每下都触发,而是等待 300ms 后才允许下一次执行--- ### 💡 应用于按钮点击(防止重复提交) ```javascript const button = document.getElementById('submitBtn'); const handleSubmit = debounce(function () { console.log('表单已提交,this:', this); // this 指向 button }, 1000, false); // 立即执行,也可以设为 true button.addEventListener('click', handleSubmit); ``` --- ### ✅ 总结功能特性 | 特性 | 支持情况 | |------------------|----------| | 防抖延迟 | ✅ | | 立即执行 | ✅ (`immediate = true`) | | 保留 `this` 上下文 | ✅ | | 传递参数 | ✅ | | 清除前次定时器 | ✅ | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值