Skip to content

Commit

Permalink
feat(utils): add throttle implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Jakub Freisler committed Mar 21, 2021
1 parent 2a83cb4 commit 0a46903
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './events';
export * from './limiters';
68 changes: 68 additions & 0 deletions packages/utils/src/limiters.spec.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { throttle } from "./limiters";

const context = {};
const args = ['anything', 2];
let callback: jest.Mock;
let throttled: (...args: unknown[])=> void;

beforeAll(() => {
jest.useFakeTimers('modern');
callback = jest.fn();
});
beforeEach(() => throttled = throttle(callback, 1000));
afterEach(() => jest.clearAllMocks());
afterAll(() => jest.useRealTimers());

describe('throttle', () => {
it('should run the callback immediately with correct context and arguments', () => {
throttled.apply(context, args);
expect(callback).toHaveBeenCalledTimes(1);
expect(callback).toHaveBeenCalledWith(...args);
expect(callback.mock.instances[0]).toBe(context);
});

describe('when 500ms have passed', () => {
it('should run the callback immediately with correct context and arguments', () => {
throttled.apply(context, args);
jest.advanceTimersByTime(500);

expect(callback).toHaveBeenCalledTimes(1);
expect(callback).toHaveBeenCalledWith(...args);
expect(callback.mock.instances[0]).toBe(context);
});
});

describe('when ran twice and 1000ms have passed', () => {
it('should run the callback twice with correct context and arguments', () => {
throttled.apply(context, args);
throttled.apply(context, args);
jest.advanceTimersByTime(1000);

expect(callback).toHaveBeenCalledTimes(2);
expect(callback).toHaveBeenCalledWith(...args);
expect(callback.mock.calls[1]).toMatchObject(args);
expect(callback.mock.instances[0]).toBe(context);
expect(callback.mock.instances[1]).toBe(context);
});
});

describe('when ran four times throughout 2000ms passed', () => {
it('should run the callback immediately with correct context and arguments', () => {
throttled.apply(context, args);
throttled.apply(context, args);
jest.advanceTimersByTime(800);
throttled.apply(context, args);
jest.advanceTimersByTime(200);
throttled.apply(context, args);
jest.advanceTimersByTime(1000);

expect(callback).toHaveBeenCalledTimes(3);
expect(callback).toHaveBeenCalledWith(...args);
expect(callback.mock.calls[1]).toMatchObject(args);
expect(callback.mock.calls[2]).toMatchObject(args);
expect(callback.mock.instances[0]).toBe(context);
expect(callback.mock.instances[1]).toBe(context);
expect(callback.mock.instances[2]).toBe(context);
});
});
});
22 changes: 22 additions & 0 deletions packages/utils/src/limiters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Throttle with ensured final and immediate invocations
// see: https://gist.github.com/beaucharman/e46b8e4d03ef30480d7f4db5a78498ca#gistcomment-3608554
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const throttle = <F extends (...args: any[])=>unknown>(callback: F, wait: number): F => {
let queuedToRun: ReturnType<Window['setTimeout']> | undefined;
let previouslyRun: number;

return function invokeFn(this: ThisType<F>, ...args: Parameters<F>) {
const now = Date.now();
queuedToRun = clearTimeout(queuedToRun) as undefined;

if (!previouslyRun || (now - previouslyRun >= wait)) {
callback.apply(this, args);
previouslyRun = now;
} else {
queuedToRun = setTimeout(
() => invokeFn.apply(this, args),
wait - (now - previouslyRun)
) as unknown as ReturnType<Window['setTimeout']>;
}
} as F;
};

0 comments on commit 0a46903

Please sign in to comment.