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)); +}