| 15 | const actualDelayMs = delayMs || 100; |
| 16 | |
| 17 | function coalescingWrapper(this: TContext) { |
| 18 | const self = context || this; |
| 19 | |
| 20 | if (inProgress) { |
| 21 | // Indicate that coalescingWrapper should be called again after the |
| 22 | // callback is no longer in progress. |
| 23 | ++inProgress; |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | if (pending) { |
| 28 | // Defer to the already-pending timer. |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | new Promise( |
| 33 | resolve => setTimeout(resolve, actualDelayMs) |
| 34 | ).then(function thenCallback() { |
| 35 | // Now that the timeout has fired, set inProgress to 1 so that |
| 36 | // (until the callback is complete and we set inProgress to 0 again) |
| 37 | // any calls to coalescingWrapper will increment inProgress to |
| 38 | // indicate that at least one other caller wants fiberCallback to be |
| 39 | // called again when the original callback is complete. |
| 40 | pending = false; |
| 41 | inProgress = 1; |
| 42 | |
| 43 | try { |
| 44 | callback.call(self); |
| 45 | } finally { |
| 46 | if (inProgress > 1) { |
| 47 | Promise.resolve().then(thenCallback); |
| 48 | pending = true; |
| 49 | } |
| 50 | inProgress = 0; |
| 51 | } |
| 52 | }); |
| 53 | } |
| 54 | |
| 55 | return wrap(coalescingWrapper, callback); |
| 56 | }; |