mirror of
https://github.com/trezor/trezor-suite.git
synced 2026-02-23 18:22:19 +01:00
feat(utils): add createCooldown util
This commit is contained in:
15
packages/utils/src/createCooldown.ts
Normal file
15
packages/utils/src/createCooldown.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Function returned by `createCooldown` returns `true` only when previous `true` was returned
|
||||
* `cooldownMs` or more millis ago, and `false` otherwise. First call always returns `true`.
|
||||
*/
|
||||
export const createCooldown = (cooldownMs: number) => {
|
||||
let last = 0;
|
||||
return () => {
|
||||
const now = Date.now();
|
||||
if (now - last >= cooldownMs) {
|
||||
last = now;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
};
|
||||
@@ -7,6 +7,7 @@ export * from './bytesToHumanReadable';
|
||||
export * from './capitalizeFirstLetter';
|
||||
export * from './cloneObject';
|
||||
export * from './countBytesInString';
|
||||
export * from './createCooldown';
|
||||
export * from './createDeferred';
|
||||
export * from './createTimeoutPromise';
|
||||
export * as enumUtils from './enumUtils';
|
||||
|
||||
14
packages/utils/tests/createCooldown.test.ts
Normal file
14
packages/utils/tests/createCooldown.test.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { createCooldown } from '../src/createCooldown';
|
||||
import { createTimeoutPromise } from '../src/createTimeoutPromise';
|
||||
|
||||
it('createCooldown', async () => {
|
||||
const cooldown = createCooldown(20);
|
||||
expect(cooldown()).toBe(true);
|
||||
expect(cooldown()).toBe(false);
|
||||
await createTimeoutPromise(10);
|
||||
expect(cooldown()).toBe(false);
|
||||
await createTimeoutPromise(15);
|
||||
expect(cooldown()).toBe(true);
|
||||
await createTimeoutPromise(5);
|
||||
expect(cooldown()).toBe(false);
|
||||
});
|
||||
@@ -151,7 +151,7 @@ describe('scheduleAction', () => {
|
||||
|
||||
it('variable timeouts', async () => {
|
||||
const TIMEOUTS = [50, 150, 100];
|
||||
const MARGIN = 5;
|
||||
const MARGIN = 10;
|
||||
|
||||
const times: number[] = [Date.now()];
|
||||
const action = (signal?: AbortSignal) => {
|
||||
|
||||
Reference in New Issue
Block a user