防抖函数的作用是确保事件在停止触发一段时间后才执行回调,避免频繁触发导致性能问题,1. 通过延迟执行并重新计时来减少函数调用次数;2. 适用于输入搜索、窗口调整等场景;3. 与节流的区别在于防抖只在停止触发后执行一次,而节流固定频率执行;4. 可通过添加leading和trailing选项优化;5. 测试时需验证延迟执行、多次触发只执行一次、leading和trailing行为是否正确,最终提升性能并保障用户体验。

防抖函数的作用是在事件被触发后,延迟一段时间执行回调,如果在延迟时间内再次被触发,则重新计时。简单来说,就是确保事件在停止触发一段时间后才执行。
function debounce(func, delay) {
let timeoutId;
return function(...args) {
const context = this; // 保持上下文
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// 示例
function handleInput(e) {
console.log('Input value:', e.target.value);
}
const debouncedInputHandler = debounce(handleInput, 300); // 延迟 300 毫秒
// 在 input 元素上使用
// <input type="text" oninput="debouncedInputHandler(event)">在某些场景下,事件会被频繁触发,例如
input
scroll
防抖和节流都是为了限制函数执行频率,但它们的实现方式不同。防抖是延迟执行,只在事件停止触发一段时间后才执行一次。而节流是控制函数执行的频率,保证在一定时间内只执行一次。 它们的应用场景也不同。防抖适合用于输入框搜索、窗口大小调整等场景,而节流适合用于滚动事件、鼠标移动事件等场景。 曾经我遇到一个问题,滚动事件导致页面频繁计算元素位置,造成页面卡顿。后来我使用了节流函数,将计算频率限制在每 100 毫秒一次,问题就解决了。
可以考虑添加 leading 和 trailing 选项。leading 选项表示是否在延迟开始前立即执行一次回调,trailing 选项表示是否在延迟结束后执行一次回调。默认情况下,只会在延迟结束后执行一次回调。
function debounce(func, delay, options = { leading: false, trailing: true }) {
let timeoutId;
let lastArgs;
let lastThis;
const { leading, trailing } = options;
function invokeFunc(time) {
timeoutId = null;
if (lastArgs) {
func.apply(lastThis, lastArgs);
lastArgs = lastThis = null;
}
}
return function(...args) {
lastArgs = args;
lastThis = this;
if (!timeoutId) {
if (leading) {
func.apply(this, args);
}
timeoutId = setTimeout(invokeFunc, delay);
} else {
clearTimeout(timeoutId);
timeoutId = setTimeout(invokeFunc, delay);
}
};
}可以使用 Jest 或 Mocha 等测试框架来测试防抖函数。 测试用例应该覆盖以下几种情况:
// 示例 Jest 测试用例
describe('debounce', () => {
jest.useFakeTimers();
it('should call the function after the delay', () => {
const func = jest.fn();
const debouncedFunc = debounce(func, 100);
debouncedFunc();
expect(func).not.toHaveBeenCalled();
jest.advanceTimersByTime(100);
expect(func).toHaveBeenCalledTimes(1);
});
});以上就是js 怎样用debounce创建防抖函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号