Sleep
Utilities for delaying code execution.
Example Usage
sleep
This utility is meant to be used for simulate async code resolution time, or to delay code execution.
This never throws an error, and internally uses setTimeout.
import { sleep } from './sleep';
await sleep(1000); // wait 1 secondDependencies
No dependencies
Auto Install
npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-sleep.json
Manual Install
sleep.ts
/** Delays code execution for a given amount of time. Never throws.*/
export const sleep = (timeInMs: number) => new Promise(res => setTimeout(res, timeInMs));Test
sleep.test.ts
import { describe, it, expect } from 'vitest';
import { repeatAsyncFnInParallel } from '../utility-framework/vitest.utils';
import { sleep } from './sleep';
describe('sleep', () => {
it('do it', async () => {
const ITERATIONS = 10_000;
const FREQUENCIES = {
success: 0,
error: 0,
};
await repeatAsyncFnInParallel(ITERATIONS, async () => {
try {
await sleep(100);
FREQUENCIES.success++;
} catch (error) {
FREQUENCIES.error++;
}
});
expect(FREQUENCIES.success).toBe(ITERATIONS);
expect(FREQUENCIES.error).toBe(0);
});
});
Command Palette
Search for a command to run...