乐闻世界logo
搜索文章和话题

How to implement sleep function in TypeScript?

1个答案

1

In TypeScript, implementing a sleep function is quite straightforward. The sleep function is typically used to pause code execution for a specified duration. This is commonly achieved in JavaScript or TypeScript by leveraging Promise along with the setTimeout function. Here, I'll demonstrate a simple example and explain how it works.

Implementing the Sleep Function in TypeScript

First, let's create a sleep function that accepts one parameter: the duration to pause (in milliseconds).

typescript
function sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); }

How to Use This Function

You can use the sleep function defined above as follows:

typescript
async function demo() { console.log('Processing some tasks...'); await sleep(2000); // Wait for 2 seconds console.log('After 2 seconds, continue with other tasks'); } demo();

How It Works

  1. Define the function: We define a function named sleep that takes a parameter ms representing the pause duration (in milliseconds).

  2. Create a Promise: The function returns a new Promise. The Promise constructor accepts an executor function with two parameters: resolve and reject. Here, we only use resolve.

  3. Use setTimeout: Inside the Promise, we call setTimeout. setTimeout is also asynchronous and executes a callback function after the specified time. In this case, the callback is resolve, meaning it resolves (completes) the Promise after the specified time.

  4. Wait for the Promise to resolve: The demo function is an asynchronous function, allowing us to use the await keyword. By await sleep(2000);, we essentially pause execution here, wait for 2 seconds, and then continue with the subsequent code.

This approach, using Promise and setTimeout, is convenient for pausing function execution wherever needed, which is particularly useful when handling asynchronous logic or simulating long-running tasks.

2024年8月2日 14:08 回复

你的答案