sleep
Create a Promise that delays for a specified amount of time.
Syntax
typescript
sleep(ms: number): Promise<void>
Parameters
ms
(number): Delay time in milliseconds
Return Value
Promise<void>
: Promise that resolves after the specified delay
Examples
Basic Usage
typescript
import { sleep } from 'radash'
async function example() {
console.log('Start')
await sleep(1000) // Delay 1 second
console.log('After 1 second')
}
Delayed Execution
typescript
import { sleep } from 'radash'
async function delayedGreeting(name: string) {
console.log('Preparing greeting...')
await sleep(2000) // Delay 2 seconds
console.log(`Hello, ${name}!`)
}
delayedGreeting('Alice')
// Output:
// Preparing greeting...
// (2 seconds later)
// Hello, Alice!
Simulate Loading State
typescript
import { sleep } from 'radash'
async function simulateLoading() {
console.log('Starting to load...')
await sleep(500)
console.log('Loading...')
await sleep(1000)
console.log('Loading complete!')
}
simulateLoading()
Retry Mechanism
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(`Attempt ${i + 1} failed, waiting to retry...`)
if (i < maxRetries - 1) {
await sleep(1000 * (i + 1)) // Incremental delay
}
}
}
throw new Error('All retries failed')
}
Animation Effects
typescript
import { sleep } from 'radash'
async function animateProgress() {
const progressBar = document.getElementById('progress')
for (let i = 0; i <= 100; i += 10) {
if (progressBar) {
progressBar.style.width = `${i}%`
progressBar.textContent = `${i}%`
}
await sleep(100) // 100ms delay between updates
}
console.log('Animation complete!')
}
animateProgress()
Rate Limiting
typescript
import { sleep } from 'radash'
class RateLimiter {
private lastRequest = 0
private minInterval = 1000 // 1 second between requests
async makeRequest(url: string) {
const now = Date.now()
const timeSinceLastRequest = now - this.lastRequest
if (timeSinceLastRequest < this.minInterval) {
const delay = this.minInterval - timeSinceLastRequest
await sleep(delay)
}
this.lastRequest = Date.now()
return fetch(url)
}
}
const limiter = new RateLimiter()
// Make multiple requests with rate limiting
async function makeRequests() {
const urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
'https://api.example.com/data3'
]
for (const url of urls) {
const response = await limiter.makeRequest(url)
console.log(`Request to ${url} completed`)
}
}
Polling
typescript
import { sleep } from 'radash'
async function pollForResult(taskId: string, maxAttempts = 10) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const response = await fetch(`/api/tasks/${taskId}`)
const task = await response.json()
if (task.status === 'completed') {
return task.result
}
if (task.status === 'failed') {
throw new Error(`Task failed: ${task.error}`)
}
console.log(`Attempt ${attempt}: Task still processing...`)
await sleep(2000) // Wait 2 seconds before next check
}
throw new Error('Task timeout')
}
const result = await pollForResult('task-123')
console.log('Task completed:', result)
Sequential Operations
typescript
import { sleep } from 'radash'
async function processSequentially(items: string[]) {
const results = []
for (const item of items) {
console.log(`Processing: ${item}`)
// Simulate processing time
await sleep(500)
const result = `Processed: ${item}`
results.push(result)
console.log(result)
}
return results
}
const items = ['item1', 'item2', 'item3', 'item4']
const processed = await processSequentially(items)
Debouncing
typescript
import { sleep } from 'radash'
class Debouncer {
private timeoutId: NodeJS.Timeout | null = null
async debounce<T>(fn: () => Promise<T>, delay: number): Promise<T> {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
}
return new Promise((resolve, reject) => {
this.timeoutId = setTimeout(async () => {
try {
const result = await fn()
resolve(result)
} catch (error) {
reject(error)
}
}, delay)
})
}
}
const debouncer = new Debouncer()
// Debounced search function
async function searchUsers(query: string) {
return debouncer.debounce(async () => {
const response = await fetch(`/api/users?q=${query}`)
return response.json()
}, 300) // 300ms delay
}
// Usage
searchUsers('john').then(users => console.log(users))
Throttling
typescript
import { sleep } from 'radash'
class Throttler {
private lastExecution = 0
private minInterval: number
constructor(minInterval: number) {
this.minInterval = minInterval
}
async throttle<T>(fn: () => Promise<T>): Promise<T> {
const now = Date.now()
const timeSinceLastExecution = now - this.lastExecution
if (timeSinceLastExecution < this.minInterval) {
const delay = this.minInterval - timeSinceLastExecution
await sleep(delay)
}
this.lastExecution = Date.now()
return fn()
}
}
const throttler = new Throttler(1000) // 1 second minimum interval
// Throttled function
async function throttledApiCall() {
return throttler.throttle(async () => {
const response = await fetch('/api/data')
return response.json()
})
}
Testing Async Code
typescript
import { sleep } from 'radash'
async function testAsyncBehavior() {
console.log('Test started')
// Simulate some async work
await sleep(100)
console.log('Async work completed')
// Simulate more async work
await sleep(200)
console.log('More async work completed')
return 'Test passed'
}
// Test the function
testAsyncBehavior().then(result => {
console.log(result)
})
Simulate Network Latency
typescript
import { sleep } from 'radash'
async function simulateNetworkRequest(url: string, latency = 100) {
console.log(`Requesting: ${url}`)
// Simulate network latency
await sleep(latency)
// Simulate response
return {
url,
data: `Response from ${url}`,
timestamp: Date.now()
}
}
// Simulate different network conditions
async function testNetworkConditions() {
console.log('Testing fast network...')
await simulateNetworkRequest('https://api.example.com/data', 50)
console.log('Testing slow network...')
await simulateNetworkRequest('https://api.example.com/data', 2000)
console.log('Testing very slow network...')
await simulateNetworkRequest('https://api.example.com/data', 5000)
}
Progressive Loading
typescript
import { sleep } from 'radash'
async function loadProgressively(items: string[]) {
const results = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
console.log(`Loading item ${i + 1}/${items.length}: ${item}`)
// Simulate loading time
await sleep(300)
const result = `Loaded: ${item}`
results.push(result)
// Update progress
const progress = ((i + 1) / items.length) * 100
console.log(`Progress: ${progress.toFixed(1)}%`)
}
return results
}
const items = ['config.json', 'user-data.json', 'settings.json', 'cache.json']
const loaded = await loadProgressively(items)
Notes
- Non-blocking: Does not block the main thread
- Precise timing: Provides accurate delay timing
- Memory efficient: Minimal memory usage
- Cancellable: Can be cancelled with AbortController
- Browser compatible: Works in both Node.js and browsers
Differences from Other Functions
sleep
: Creates a delay with PromisesetTimeout
: Callback-based, less convenient with async/awaitsetInterval
: Repeats at intervals, while sleep is one-timesleep()
: More intuitive for async operations
Performance
- Time Complexity: O(1) for the delay itself
- Memory: Minimal memory usage
- Use Cases: Rate limiting, polling, animations, testing