-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
42 lines (42 loc) · 1.07 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Stop execution for a specified amount of time.
*
* @param ms The time in milliseconds to wait before resolving the Promise.
* @param cb An optional callback function to execute before resolving the Promise.
* @returns A Promise that resolves after the specified time has elapsed.
*
* @example
* #### Basic usage
* ```ts
* // using async/await
* async function main() {
* console.log('Before timeout.')
* await timeout(1000, () => console.log('A second has passed!'))
* console.log('After timeout.')
* }
* main()
* // Before timeout.
* // A second has passed!
* // After timeout.
*
* // using Promise.then()
* console.log('Before timeout.')
* timeout(
* 1000,
* () => console.log('A second has passed!')
* ).then(
* () => console.log('Then...')
* )
* console.log('After timeout.')
* // Before timeout.
* // After timeout.
* // A second has passed!
* // Then...
* ```
* @category Misc
*/
export const timeout = <R = void>(ms: number, cb?: () => R) => {
return new Promise<R>((resolve) =>
setTimeout(() => resolve(cb?.() as R), ms)
)
}