防抖函数的核心是延迟执行函数并在延迟内重新计时,确保事件停止触发后才执行,适用于搜索建议、窗口调整等场景;1. func.apply(context, args)用于绑定this上下文和传递参数,确保函数在正确上下文中执行;2. 使用apply而非func(...args)是为了精确控制this值,尤其在事件处理中保持上下文一致;3. 立即执行的防抖通过immediate参数和callnow判断实现首次触发立即执行;4. 防抖与节流的区别在于防抖是“最后一次有效”,节流是“周期内只执行一次”;5. 节流可通过时间戳或requestanimationframe实现,后者更契合浏览器渲染节奏,提升性能;6. 选择依据:防抖用于停止后执行,节流用于持续中定期执行,根据场景需求决定。

防抖函数的核心在于,延迟执行一个函数,如果在延迟时间内再次触发,则重新计时。这样可以避免函数被频繁调用,提高性能。

function debounce(func, delay) {
let timeoutId;
return function(...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}防抖的核心在于,当事件被触发时,不是立即执行事件处理函数,而是给出一个延迟时间。如果在延迟时间内,事件再次被触发,就重新计算延迟时间。只有在延迟时间结束后,才会执行事件处理函数。
如何理解
func.apply(context, args)

func.apply(context, args)
this
context
args
context
func
this
context
null
undefined
this
window
this
undefined
debounce
context
this
this
args
func
debounce
args
...args
func
示例:
function myFunction(arg1, arg2) {
console.log("arg1:", arg1, "arg2:", arg2);
console.log("this:", this);
}
const myObject = {
name: "My Object"
};
// 使用 apply 调用 myFunction,并设置 this 为 myObject,传递两个参数
myFunction.apply(myObject, [10, 20]);
// 输出:
// arg1: 10 arg2: 20
// this: {name: 'My Object'}为什么要使用
apply
func(...args)
虽然
func(...args)
apply
this
apply
this
防抖函数有哪些应用场景?
输入框搜索建议: 当用户在输入框中输入内容时,如果每次输入都发起搜索请求,会给服务器带来很大的压力。使用防抖函数,可以在用户停止输入一段时间后,才发起搜索请求,减少请求次数。
窗口大小调整: 当窗口大小调整时,可能会触发一些重新布局的操作。使用防抖函数,可以在窗口大小调整结束后,才执行重新布局的操作,避免频繁的布局计算。
按钮点击: 防止用户快速连续点击按钮,导致重复提交数据。
如何实现立即执行的防抖函数?
function debounce(func, delay, immediate) {
let timeoutId;
return function(...args) {
const context = this;
const callNow = immediate && !timeoutId;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null; // 清除 timeoutId
if (!immediate) {
func.apply(context, args);
}
}, delay);
if (callNow) {
func.apply(context, args);
}
};
}这段代码的关键在于
immediate
immediate
true
callNow
timeoutId = null
callNow
防抖函数和节流函数有什么区别?
防抖函数是在一段时间内,只执行一次函数。如果在该时间内再次触发,则重新计时。而节流函数是在一段时间内,最多执行一次函数。无论在该时间内触发多少次,都只执行一次。
简单来说,防抖是“最后一次算数”,节流是“一段时间内只算一次”。
手写一个节流函数:
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const context = this;
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
}
};
}这个节流函数通过记录上一次执行的时间
lastTime
lastTime
delay
lastTime
delay
使用
requestAnimationFrame
使用
requestAnimationFrame
function throttle(func) {
let waiting = false;
return function(...args) {
const context = this;
if (!waiting) {
waiting = true;
requestAnimationFrame(() => {
func.apply(context, args);
waiting = false;
});
}
};
}requestAnimationFrame
如何选择防抖函数和节流函数?
选择哪个函数取决于具体的应用场景和需求。如果需要确保在事件停止触发后执行一次,则选择防抖函数。如果需要在一段时间内定期执行,则选择节流函数。
以上就是js中如何实现防抖函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号