Skip to content

Commit

Permalink
fix(esl-utils): incorrect throttle behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
fshovchko committed Apr 6, 2023
1 parent 913e93e commit 918944d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ describe('ESLEventUtils.decorate proxy', () => {
window.dispatchEvent(event);
jest.advanceTimersByTime(10);
expect(fn).lastCalledWith(event);
jest.advanceTimersByTime(DEFAULT_TIMEOUT + 100);
});

test('Proxy scroll happens throttled (multiple events received once in bounds of threshold)', ()=> {
Expand Down
2 changes: 1 addition & 1 deletion src/modules/esl-utils/async/test/throttle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe('async/throttle', () => {
jest.advanceTimersByTime(100);
expect(fn).toBeCalledTimes(2);
expect(throttled()).toBeUndefined();
expect(fn).toBeCalledTimes(3);
expect(fn).toBeCalledTimes(2);
});

test('test context', () => {
Expand Down
24 changes: 12 additions & 12 deletions src/modules/esl-utils/async/throttle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@ export function throttle<F extends AnyToAnyFnSignature>(fn: F, threshold = 250,

function throttledSubject(...args: any[]): void {
const now = Date.now();
const lastThreshold = last + threshold;

if (!last || now >= last + threshold) {
last = now;
fn.apply(this, args);
}
deferred = createDeferred();

deferred = deferred || createDeferred();
(typeof timeout === 'number') && clearTimeout(timeout);
timeout = window.setTimeout(() => {
if (!last || now >= lastThreshold) {
last = now;
timeout = null;
// fn.apply to save call context
deferred!.resolve(fn.apply(thisArg || this, args));
deferred = null;
}, threshold);
deferred.resolve(fn.apply(thisArg || this, args));
} else {
(typeof timeout === 'number') && clearTimeout(timeout);
timeout = window.setTimeout(() => {
last = Date.now();
timeout = null;
deferred!.resolve(fn.apply(thisArg || this, args));
}, lastThreshold - now);
}
}
Object.defineProperty(throttledSubject, 'promise', {
get: () => deferred ? deferred.promise : Promise.resolve()
Expand Down

0 comments on commit 918944d

Please # to comment.