Skip to content

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()

注意事项

  1. 异步函数: 必须在 async 函数中使用
  2. 非阻塞: 不会阻塞主线程
  3. 精度: 实际延迟可能略大于指定时间
  4. 取消: 不支持取消操作

与其他函数的区别

  • sleep: 创建延迟 Promise
  • setTimeout: 原生方法,需要回调
  • setInterval: 重复执行
  • Promise.resolve: 立即解析

性能

  • 时间复杂度: O(1)
  • 内存使用: 最小
  • 适用场景: 异步编程、测试、动画

Released under the MIT License.