Search
⌘K

Sleep

Utilities for delaying code execution.

Example Usage

import { sleep } from './sleep';

// NOTE:
// This utility is meant to be used for simulate async code resolution time, or to delay code execution.
// This never throws an error.

await sleep(1000); // wait 1 second

Dependencies

No dependencies

Auto Install

npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-sleep.json

Manual Install

sleep.ts
/**
 * Source: http://localhost:3000
 */

/**
 * 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...