source: node_modules/es-toolkit/dist/function/debounce.mjs

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 1.6 KB
Line 
1function debounce(func, debounceMs, { signal, edges } = {}) {
2 let pendingThis = undefined;
3 let pendingArgs = null;
4 const leading = edges != null && edges.includes('leading');
5 const trailing = edges == null || edges.includes('trailing');
6 const invoke = () => {
7 if (pendingArgs !== null) {
8 func.apply(pendingThis, pendingArgs);
9 pendingThis = undefined;
10 pendingArgs = null;
11 }
12 };
13 const onTimerEnd = () => {
14 if (trailing) {
15 invoke();
16 }
17 cancel();
18 };
19 let timeoutId = null;
20 const schedule = () => {
21 if (timeoutId != null) {
22 clearTimeout(timeoutId);
23 }
24 timeoutId = setTimeout(() => {
25 timeoutId = null;
26 onTimerEnd();
27 }, debounceMs);
28 };
29 const cancelTimer = () => {
30 if (timeoutId !== null) {
31 clearTimeout(timeoutId);
32 timeoutId = null;
33 }
34 };
35 const cancel = () => {
36 cancelTimer();
37 pendingThis = undefined;
38 pendingArgs = null;
39 };
40 const flush = () => {
41 invoke();
42 };
43 const debounced = function (...args) {
44 if (signal?.aborted) {
45 return;
46 }
47 pendingThis = this;
48 pendingArgs = args;
49 const isFirstCall = timeoutId == null;
50 schedule();
51 if (leading && isFirstCall) {
52 invoke();
53 }
54 };
55 debounced.schedule = schedule;
56 debounced.cancel = cancel;
57 debounced.flush = flush;
58 signal?.addEventListener('abort', cancel, { once: true });
59 return debounced;
60}
61
62export { debounce };
Note: See TracBrowser for help on using the repository browser.