Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created May 5, 2024 04:56
Show Gist options
  • Save amitasaurus/e729c08efa2442d88ef75f39fc586497 to your computer and use it in GitHub Desktop.
Save amitasaurus/e729c08efa2442d88ef75f39fc586497 to your computer and use it in GitHub Desktop.
Implement a throttle function which accepts a callback function and a wait duration. Calling throttle() returns a function which throttled invocations of the callback function following the described behaviour.
/**
* Throttling is a technique used to control how many times we allow a function to be executed over time.
* When a JavaScript function is said to be throttled with a wait time of X milliseconds, it can only be invoked at most once every X milliseconds.
* The callback is invoked immediately and cannot be invoked again for the rest of the wait duration.
*/
type ThrottleFunction<T extends any[]> = (...args: T) => any;
export default function throttle<T extends any[]>(
func: ThrottleFunction<T>,
wait: number
): ThrottleFunction<T> {
let timer: ReturnType<typeof setTimeout> | null = null;
return function (this: any, ...args: T) {
if (!timer) {
func.apply(this, args);
timer = setTimeout(() => {
clearTimeout(timer!);
timer = null;
}, wait);
}
};
}
let i = 0;
function increment() {
i++;
}
const throttledIncrement = throttle(increment, 100);
throttledIncrement();
console.log(i); //1
setTimeout(() => {
throttledIncrement();
console.log(i); //1
}, 50);
setTimeout(() => {
throttledIncrement();
console.log(i); //2
}, 101);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment