1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 02:44:45 +00:00

feat(packages/stdlib): add sleep async util

This commit is contained in:
2024-10-24 07:30:41 +07:00
parent 5bc3dd5ee0
commit 9b5eef04c7
3 changed files with 40 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
export * from './sleep';
export * from './tryIt';

View File

@@ -0,0 +1,19 @@
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { sleep } from '.';
describe('sleep', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
});
it('delay execution by the specified amount of time', async () => {
const start = performance.now();
const delay = 100;
await sleep(delay);
const end = performance.now();
expect(end - start).toBeGreaterThanOrEqual(delay);
});
});

View File

@@ -0,0 +1,19 @@
/**
* @name sleep
* @category Async
* @description Delays the execution of the current function by the specified amount of time
*
* @param {number} ms - The amount of time to delay the execution of the current function
* @returns {Promise<void>} - A promise that resolves after the specified amount of time
*
* @example
* await sleep(1000);
*
* @example
* sleep(1000).then(() => {
* console.log('Hello, World!');
* });
*/
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}