---
title: "sleepWithCancel"
description: "[object Object]"
canonical_url: "https://core.mhaibaraai.cn/en/docs/utilities/async/sleep-with-cancel"
---
# sleepWithCancel

> [object Object]

## Usage

`sleepWithCancel` creates a cancellable delay, returning both a promise and a cancel function.

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

const { promise, cancel } = sleepWithCancel(5000)

// Cancel the delay from elsewhere
setTimeout(() => {
  cancel() // Abort the delay
}, 2000)

try {
  await promise
  console.log('Executed after 5 seconds')
}
catch (error) {
  console.log('Delay was cancelled')
}
```

## API

### `sleepWithCancel(ms)`

Return a cancellable delay: a promise and a cancel function.

### Parameters

**ms** (`number`) *required*: The delay duration in milliseconds.

### Returns

**returns** (`{ promise: Promise<void>; cancel: () => void }`): An object containing the delay promise and a cancel function.

## 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](https://core.mhaibaraai.cn/sitemap.md) for all pages.
