Small throttle implementation
Wanted to implement a throttle function in as few lines as possible (while maintaining code readability).
by Yair Even Or
JavaScript
// Allow callback to run at most 1 time per 100ms
window.addEventListener("resize", throttle(callback, 100));
function callback (e) { console.log(e) }
function throttle (callback, limit) {
var wait = false; // Initially, we're not waiting
return function (arguments) { // We return a throttled function
console.log(1111, arguments)
if (!wait) { // If we're not waiting
callback.call(arguments); // Execute users function
wait = true; // Prevent future invocations
setTimeout(function () { // After a period of time
wait = false; // And allow future invocations
}, limit);
}
}
}