|
Last change
on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago |
|
Added visualizations
|
-
Property mode
set to
100644
|
|
File size:
825 bytes
|
| Line | |
|---|
| 1 | import { debounce } from './debounce.mjs';
|
|---|
| 2 |
|
|---|
| 3 | function throttle(func, throttleMs, { signal, edges = ['leading', 'trailing'] } = {}) {
|
|---|
| 4 | let pendingAt = null;
|
|---|
| 5 | const debounced = debounce(function (...args) {
|
|---|
| 6 | pendingAt = Date.now();
|
|---|
| 7 | func.apply(this, args);
|
|---|
| 8 | }, throttleMs, { signal, edges });
|
|---|
| 9 | const throttled = function (...args) {
|
|---|
| 10 | if (pendingAt == null) {
|
|---|
| 11 | pendingAt = Date.now();
|
|---|
| 12 | }
|
|---|
| 13 | if (Date.now() - pendingAt >= throttleMs) {
|
|---|
| 14 | pendingAt = Date.now();
|
|---|
| 15 | func.apply(this, args);
|
|---|
| 16 | debounced.cancel();
|
|---|
| 17 | debounced.schedule();
|
|---|
| 18 | return;
|
|---|
| 19 | }
|
|---|
| 20 | debounced.apply(this, args);
|
|---|
| 21 | };
|
|---|
| 22 | throttled.cancel = debounced.cancel;
|
|---|
| 23 | throttled.flush = debounced.flush;
|
|---|
| 24 | return throttled;
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | export { throttle };
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.