JavaScript 节流函数封装:限制事件触发频率
好的,以下是一个基本的节流函数的封装:
function throttle(func, delay) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
};
}
这个函数接受两个参数:
- 'func'是要执行的函数。
- 'delay'是节流的时间间隔,以毫秒为单位。
调用这个函数会返回一个新的函数,这个函数会在指定的时间间隔内只执行一次。
例如,以下代码使用上面的'throttle'函数来防止滚动事件过于频繁地触发:
window.addEventListener('scroll', throttle(function() {
console.log('Scrolling...');
}, 200));
这将在滚动事件触发时,每200毫秒最多只执行一次'console.log('Scrolling...')'。
原文地址: https://www.cveoy.top/t/topic/mjcY 著作权归作者所有。请勿转载和采集!