---
title: "sleepWithCancel"
description: "可取消的延迟函数，返回 Promise 和取消函数"
seo_title: "sleepWithCancel"
seo_description: {"Return a cancellable delay":"a promise plus a cancel function so you can abort a pending timeout before it resolves in async flows."}
canonical_url: "https://core.mhaibaraai.cn/docs/utilities/async/sleep-with-cancel"
---
# sleepWithCancel

> 可取消的延迟函数，返回 Promise 和取消函数

## 用法

`sleepWithCancel` 函数用于创建可取消的延迟，返回 Promise 和取消函数。

```ts
import { sleepWithCancel } from '@movk/core'

const { promise, cancel } = sleepWithCancel(5000)

// 在另一个地方取消延迟
setTimeout(() => {
  cancel() // 取消延迟
}, 2000)

try {
  await promise
  console.log('5秒后执行')
}
catch (error) {
  console.log('延迟被取消')
}
```

## API

### `sleepWithCancel(ms)`

可取消的延迟函数，返回 Promise 和取消函数。

### 参数

**ms** (`number`) *required*: 延迟时间（毫秒）。

### 返回值

**返回值** (`{ promise: Promise<void>; cancel: () => void }`): 包含 Promise 和取消函数的对象。

## Changelog

See commit history for [src/utilities/async/sleepWithCancel.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/utilities/async/sleepWithCancel.ts).


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
