mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-18 19:59:20 +00:00
feat: added debounce delay to auto reply
reply only last message received within 3 seconds
This commit is contained in:
41
backend/src/helpers/Debounce.ts
Normal file
41
backend/src/helpers/Debounce.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
interface Timeout {
|
||||
id: number;
|
||||
timeout: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
const timeouts: Timeout[] = [];
|
||||
|
||||
const findAndClearTimeout = (ticketId: number) => {
|
||||
if (timeouts.length > 0) {
|
||||
const timeoutIndex = timeouts.findIndex(timeout => timeout.id === ticketId);
|
||||
|
||||
if (timeoutIndex !== -1) {
|
||||
clearTimeout(timeouts[timeoutIndex].timeout);
|
||||
timeouts.splice(timeoutIndex, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const debounce = (
|
||||
func: { (): Promise<void>; (...args: never[]): void },
|
||||
wait: number,
|
||||
ticketId: number
|
||||
) => {
|
||||
return function executedFunction(...args: never[]): void {
|
||||
const later = () => {
|
||||
findAndClearTimeout(ticketId);
|
||||
func(...args);
|
||||
};
|
||||
|
||||
findAndClearTimeout(ticketId);
|
||||
|
||||
const newTimeout = {
|
||||
id: ticketId,
|
||||
timeout: setTimeout(later, wait)
|
||||
};
|
||||
|
||||
timeouts.push(newTimeout);
|
||||
};
|
||||
};
|
||||
|
||||
export { debounce };
|
||||
Reference in New Issue
Block a user