sleep
創建一個延遲指定時間的 Promise。
語法
typescript
sleep(ms: number): Promise<void>
參數
ms
(number): 延遲的毫秒數
返回值
Promise<void>
: 延遲指定時間後解析的 Promise
示例
基本用法
typescript
import { sleep } from 'radash'
async function example() {
console.log('開始')
await sleep(1000) // 延遲1秒
console.log('1秒後')
}
延遲執行
typescript
import { sleep } from 'radash'
async function delayedGreeting(name: string) {
console.log('准備問候...')
await sleep(2000) // 延遲2秒
console.log(`你好,${name}!`)
}
delayedGreeting('Alice')
// 輸出:
// 准備問候...
// (2秒後)
// 你好,Alice!
模擬加載狀態
typescript
import { sleep } from 'radash'
async function simulateLoading() {
console.log('開始加載...')
await sleep(500)
console.log('加載中...')
await sleep(1000)
console.log('加載完成!')
}
simulateLoading()
重試機制
typescript
import { sleep } from 'radash'
async function fetchWithRetry(url: string, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url)
if (response.ok) {
return await response.json()
}
} catch (error) {
console.log(`嘗試 ${i + 1} 失敗,等待重試...`)
if (i < maxRetries - 1) {
await sleep(1000 * (i + 1)) // 遞增延遲
}
}
}
throw new Error('所有重試都失敗了')
}
動畫效果
typescript
import { sleep } from 'radash'
async function animateProgress() {
const steps = ['初始化', '加載數據', '處理信息', '完成']
for (const step of steps) {
console.log(step)
await sleep(800)
}
}
animateProgress()
批量處理
typescript
import { sleep } from 'radash'
async function processBatch(items: any[]) {
const results = []
for (const item of items) {
// 處理項目
const result = await processItem(item)
results.push(result)
// 避免過載,在請求之間添加延遲
await sleep(100)
}
return results
}
async function processItem(item: any) {
// 模擬處理邏輯
return { ...item, processed: true }
}
超時處理
typescript
import { sleep } from 'radash'
async function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number
): Promise<T> {
const timeoutPromise = sleep(timeoutMs).then(() => {
throw new Error('操作超時')
})
return Promise.race([promise, timeoutPromise])
}
// 使用示例
const slowOperation = new Promise(resolve => {
setTimeout(() => resolve('完成'), 5000)
})
try {
const result = await withTimeout(slowOperation, 3000)
console.log(result)
} catch (error) {
console.error('超時:', error.message)
}
輪詢機制
typescript
import { sleep } from 'radash'
async function pollForResult(checkFn: () => boolean, interval = 1000) {
while (!checkFn()) {
await sleep(interval)
}
return true
}
// 使用示例
let counter = 0
const checkCondition = () => {
counter++
return counter >= 5
}
await pollForResult(checkCondition, 500)
console.log('條件滿足!')
模擬用戶交互
typescript
import { sleep } from 'radash'
async function simulateUserTyping(text: string, delay = 100) {
for (const char of text) {
process.stdout.write(char)
await sleep(delay)
}
console.log()
}
await simulateUserTyping('Hello, World!', 50)
游戲邏輯
typescript
import { sleep } from 'radash'
class Game {
private playerHealth = 100
async takeDamage(damage: number) {
this.playerHealth -= damage
console.log(`受到 ${damage} 點傷害,剩余生命值: ${this.playerHealth}`)
if (this.playerHealth <= 0) {
console.log('游戲結束!')
return
}
// 等待一秒後繼續
await sleep(1000)
console.log('繼續游戲...')
}
}
const game = new Game()
await game.takeDamage(30)
測試輔助
typescript
import { sleep } from 'radash'
async function testAsyncBehavior() {
console.log('開始測試')
// 模擬異步操作
await sleep(100)
console.log('異步操作1完成')
await sleep(200)
console.log('異步操作2完成')
await sleep(300)
console.log('異步操作3完成')
console.log('測試完成')
}
testAsyncBehavior()
錯誤處理
typescript
import { sleep } from 'radash'
async function safeOperation() {
try {
console.log('開始操作')
await sleep(1000)
// 模擬可能失敗的操作
if (Math.random() > 0.5) {
throw new Error('操作失敗')
}
console.log('操作成功')
} catch (error) {
console.error('操作失敗:', error.message)
// 等待後重試
await sleep(2000)
console.log('准備重試...')
}
}
safeOperation()
注意事項
- 異步函數: 必須在 async 函數中使用
- 非阻塞: 不會阻塞主線程
- 精度: 實際延遲可能略大於指定時間
- 取消: 不支持取消操作
與其他函數的區別
sleep
: 創建延遲 PromisesetTimeout
: 原生方法,需要回調setInterval
: 重復執行Promise.resolve
: 立即解析
性能
- 時間復雜度: O(1)
- 內存使用: 最小
- 適用場景: 異步編程、測試、動畫