超级方便!!!!!封装在common.js文件需要时调用!
/**
* 函数防抖
*/
function debounce(fn, wait = 1000) {
let timer;
return function () {
let context = this;
let args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, wait)
}
}
/**
* 函数节流
*/
function throttle(fn, wait = 1000) {
let timer;
return function () {
if (timer != null) return;
let context = this;
let args = arguments;
fn.apply(context, args);
timer = setTimeout(() => {
timer = null;
}, wait);
}
}
使用方法:
btnDebounce: debounce(function (str1, str2) {
console.log(str1, str2);
}, 2000),
btnDethrottle: throttle(function (str1, str2) {
console.log(str1, str2);
}, 2000),

本文介绍了JavaScript中两种重要的函数优化技巧——防抖(debounce)和节流(throttle)。提供了详细的函数实现,并展示了如何在实际项目中通过debounce和throttle函数来提高性能,例如在事件监听器中限制函数的执行频率。
412

被折叠的 条评论
为什么被折叠?



