From b275e6db1fa8f3b51aef6b80a941f4baaf202966 Mon Sep 17 00:00:00 2001 From: tsa96 Date: Sun, 15 Dec 2024 04:10:05 +0000 Subject: [PATCH] feat(utils): sleep fn --- libs/util-fn/src/index.ts | 1 + libs/util-fn/src/sleep.spec.ts | 24 ++++++++++++++++++++++++ libs/util-fn/src/sleep.ts | 7 +++++++ 3 files changed, 32 insertions(+) create mode 100644 libs/util-fn/src/sleep.spec.ts create mode 100644 libs/util-fn/src/sleep.ts diff --git a/libs/util-fn/src/index.ts b/libs/util-fn/src/index.ts index d7fd8e9e0..3453c98a3 100644 --- a/libs/util-fn/src/index.ts +++ b/libs/util-fn/src/index.ts @@ -16,3 +16,4 @@ export * from './pick'; export * from './omit'; export * from './magic'; export * from './approx-eq'; +export * from './sleep'; diff --git a/libs/util-fn/src/sleep.spec.ts b/libs/util-fn/src/sleep.spec.ts new file mode 100644 index 000000000..e594b43d3 --- /dev/null +++ b/libs/util-fn/src/sleep.spec.ts @@ -0,0 +1,24 @@ +import { sleep } from './sleep'; + +describe('sleep', () => { + it('resolves after the specified duration', async () => { + const start = Date.now(); + await sleep(100); + const end = Date.now(); + expect(end - start).toBeGreaterThanOrEqual(100); + }); + + it('resolves after a long duration', async () => { + const start = Date.now(); + await sleep(1000); + const end = Date.now(); + expect(end - start).toBeGreaterThanOrEqual(1000); + }); + + it('handles negative duration by resolving immediately', async () => { + const start = Date.now(); + await sleep(-100); + const end = Date.now(); + expect(end - start).toBeLessThan(10); + }); +}); diff --git a/libs/util-fn/src/sleep.ts b/libs/util-fn/src/sleep.ts new file mode 100644 index 000000000..c073c8e79 --- /dev/null +++ b/libs/util-fn/src/sleep.ts @@ -0,0 +1,7 @@ +export function sleep(duration: number): Promise { + if (duration < 0) { + return Promise.resolve(); + } + + return new Promise((resolve) => setTimeout(resolve, duration)); +}