|
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.7 KB
|
| Rev | Line | |
|---|
| [a762898] | 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|---|
| 4 |
|
|---|
| 5 | function debounce(func, debounceMs, { signal, edges } = {}) {
|
|---|
| 6 | let pendingThis = undefined;
|
|---|
| 7 | let pendingArgs = null;
|
|---|
| 8 | const leading = edges != null && edges.includes('leading');
|
|---|
| 9 | const trailing = edges == null || edges.includes('trailing');
|
|---|
| 10 | const invoke = () => {
|
|---|
| 11 | if (pendingArgs !== null) {
|
|---|
| 12 | func.apply(pendingThis, pendingArgs);
|
|---|
| 13 | pendingThis = undefined;
|
|---|
| 14 | pendingArgs = null;
|
|---|
| 15 | }
|
|---|
| 16 | };
|
|---|
| 17 | const onTimerEnd = () => {
|
|---|
| 18 | if (trailing) {
|
|---|
| 19 | invoke();
|
|---|
| 20 | }
|
|---|
| 21 | cancel();
|
|---|
| 22 | };
|
|---|
| 23 | let timeoutId = null;
|
|---|
| 24 | const schedule = () => {
|
|---|
| 25 | if (timeoutId != null) {
|
|---|
| 26 | clearTimeout(timeoutId);
|
|---|
| 27 | }
|
|---|
| 28 | timeoutId = setTimeout(() => {
|
|---|
| 29 | timeoutId = null;
|
|---|
| 30 | onTimerEnd();
|
|---|
| 31 | }, debounceMs);
|
|---|
| 32 | };
|
|---|
| 33 | const cancelTimer = () => {
|
|---|
| 34 | if (timeoutId !== null) {
|
|---|
| 35 | clearTimeout(timeoutId);
|
|---|
| 36 | timeoutId = null;
|
|---|
| 37 | }
|
|---|
| 38 | };
|
|---|
| 39 | const cancel = () => {
|
|---|
| 40 | cancelTimer();
|
|---|
| 41 | pendingThis = undefined;
|
|---|
| 42 | pendingArgs = null;
|
|---|
| 43 | };
|
|---|
| 44 | const flush = () => {
|
|---|
| 45 | invoke();
|
|---|
| 46 | };
|
|---|
| 47 | const debounced = function (...args) {
|
|---|
| 48 | if (signal?.aborted) {
|
|---|
| 49 | return;
|
|---|
| 50 | }
|
|---|
| 51 | pendingThis = this;
|
|---|
| 52 | pendingArgs = args;
|
|---|
| 53 | const isFirstCall = timeoutId == null;
|
|---|
| 54 | schedule();
|
|---|
| 55 | if (leading && isFirstCall) {
|
|---|
| 56 | invoke();
|
|---|
| 57 | }
|
|---|
| 58 | };
|
|---|
| 59 | debounced.schedule = schedule;
|
|---|
| 60 | debounced.cancel = cancel;
|
|---|
| 61 | debounced.flush = flush;
|
|---|
| 62 | signal?.addEventListener('abort', cancel, { once: true });
|
|---|
| 63 | return debounced;
|
|---|
| 64 | }
|
|---|
| 65 |
|
|---|
| 66 | exports.debounce = debounce;
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.