2024-04-25 14:56:13 +03:00
|
|
|
# delay
|
|
|
|
|
|
|
|
Delays the execution of code for a specified number of milliseconds.
|
|
|
|
|
2024-06-04 11:19:26 +03:00
|
|
|
This function returns a Promise that resolves after the specified delay, allowing you to use it
|
2024-04-25 14:56:13 +03:00
|
|
|
with async/await to pause execution.
|
2024-06-15 09:20:42 +03:00
|
|
|
It also supports an optional AbortSignal to cancel the delay.
|
2024-04-25 14:56:13 +03:00
|
|
|
|
|
|
|
## Signature
|
|
|
|
|
|
|
|
```typescript
|
2024-06-15 09:20:42 +03:00
|
|
|
function delay(ms: number, options?: DelayOptions): Promise<void>;
|
2024-04-25 14:56:13 +03:00
|
|
|
```
|
|
|
|
|
2024-06-04 11:19:26 +03:00
|
|
|
### Parameters
|
2024-04-25 14:56:13 +03:00
|
|
|
|
|
|
|
- `ms` (`number`): The number of milliseconds to delay.
|
2024-06-15 09:20:42 +03:00
|
|
|
- `options` (`DelayOptions`, optional): An options object.
|
|
|
|
- `signal` (`AbortSignal`, optional): An optional `AbortSignal` to cancel the delay.
|
2024-04-25 14:56:13 +03:00
|
|
|
|
|
|
|
### Returns
|
|
|
|
|
|
|
|
(`Promise<void>`): A Promise that resolves after the specified delay.
|
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
2024-06-15 09:20:42 +03:00
|
|
|
### Basic Usage
|
|
|
|
|
2024-04-25 14:56:13 +03:00
|
|
|
```typescript
|
|
|
|
async function foo() {
|
|
|
|
console.log('Start');
|
|
|
|
await delay(1000); // Delays execution for 1 second
|
|
|
|
console.log('End');
|
|
|
|
}
|
|
|
|
|
|
|
|
foo();
|
|
|
|
```
|
2024-06-15 09:20:42 +03:00
|
|
|
|
|
|
|
### Using with an AbortSignal
|
|
|
|
|
|
|
|
```typescript
|
|
|
|
async function foo() {
|
|
|
|
const controller = new AbortController();
|
|
|
|
const signal = controller.signal;
|
|
|
|
|
|
|
|
setTimeout(() => controller.abort(), 50); // Will cancel the delay after 50ms
|
|
|
|
try {
|
|
|
|
await delay(1000, { signal });
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error); // Will log 'The operation was aborted'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|