节流技术优化思路
- 理解节流原理:节流的核心思想是在一定时间间隔内,无论触发多少次事件,都只执行一次回调函数。这可以有效控制滚动事件触发频率,避免频繁执行复杂逻辑导致的性能问题。
- 确定节流时间间隔:根据具体业务场景和复杂逻辑的执行时间,合理选择节流时间间隔。如果时间间隔过短,可能无法达到优化性能的目的;时间间隔过长,可能影响用户体验。
- 应用到滚动事件:将节流函数应用到每个元素的滚动事件上,确保每个滚动事件在节流时间间隔内只执行一次复杂逻辑。
实现节流函数
function throttle(func, wait, options = {}) {
let timeout;
let previous = 0;
const { leading = true, trailing = true } = options;
return function(...args) {
const now = new Date().getTime();
if (!previous &&!leading) previous = now;
const remaining = wait - (now - previous);
clearTimeout(timeout);
if (remaining <= 0) {
timeout = setTimeout(() => {
previous = trailing? 0 : now;
func.apply(this, args);
}, 0);
} else if (trailing) {
timeout = setTimeout(() => {
func.apply(this, args);
previous = now;
}, remaining);
}
};
}
// 使用示例
const complexScrollLogic = function() {
// 复杂的滚动处理逻辑
console.log('执行复杂滚动逻辑');
};
const scrollElement1 = document.getElementById('element1');
const scrollElement2 = document.getElementById('element2');
const throttledFunction1 = throttle(complexScrollLogic, 300, { leading: true, trailing: true });
const throttledFunction2 = throttle(complexScrollLogic, 500, { leading: true, trailing: true });
scrollElement1.addEventListener('scroll', throttledFunction1);
scrollElement2.addEventListener('scroll', throttledFunction2);
// 取消节流示例
function cancelThrottle(throttledFunc) {
clearTimeout(throttledFunc.timeout);
}
// 假设要取消element1的节流
cancelThrottle(throttledFunction1);
代码说明
- throttle函数:接受三个参数,
func
是要执行的复杂逻辑函数,wait
是节流时间间隔,options
是配置对象,用于控制是否在开始和结束时执行函数。
- 内部变量:
timeout
用于存储定时器,previous
记录上一次执行的时间。
- 逻辑判断:根据当前时间和上一次执行时间计算剩余时间
remaining
。如果 remaining
小于等于 0,立即执行函数,并根据 trailing
配置决定是否重置 previous
。如果 remaining
大于 0 且 trailing
为 true
,则设置一个定时器在 remaining
时间后执行函数。
- 取消节流:
cancelThrottle
函数用于取消节流,通过清除 throttledFunc
中的定时器来实现。