Event handling utility functions in TypeScript are functions that are used to handle events in a web page. Events are actions or occurrences that happen in the browser, such as a mouse click or a keyboard press.
events.ts
Copy export const on = (
element: EventTarget,
event: string,
handler: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions
): void => {
element.addEventListener(event, handler, options);
};
export const off = (
element: EventTarget,
event: string,
handler: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions
): void => {
element.removeEventListener(event, handler, options);
};
export const preventDefault = (event: Event): void => {
event.preventDefault();
};
export const stopPropagation = (event: Event): void => {
event.stopPropagation();
};
export const debounce = <F extends (...args: any[]) => void>(
func: F,
delay: number
): ((...args: Parameters<F>) => void) => {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Parameters<F>): void => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
};
export const throttle = <F extends (...args: any[]) => void>(
func: F,
limit: number
): ((...args: Parameters<F>) => void) => {
let inThrottle = false;
return (...args: Parameters<F>): void => {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
};