The problem
In continuously triggered events like scrolling, dragging, need to control function execution frequency
The solution
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}Parameters
funcfunctionFunction to throttle
limitnumberTime limit in milliseconds
Put it to work
// Handle scroll events
const handleScroll = throttle(() => {
console.log('Scrolling...');
}, 1000);
window.addEventListener('scroll', handleScroll);