Skip to main content

sleep

@rotorsoft/act-root


@rotorsoft/act-root / act/src / sleep

Function: sleep()

sleep(ms?): Promise<unknown>

Defined in: libs/act/src/utils.ts:492

Pauses async execution for a specified duration.

This is a simple async utility for adding delays in your code. When called without arguments, it uses the configured sleep duration from config().sleepMs, which defaults to 100ms in development and 0ms in test environments.

The framework uses this internally in store adapters to simulate I/O delays in the InMemoryStore.

Note: In test environments (NODE_ENV=test), the default sleep duration is 0ms to keep tests fast.

Parameters

ms?

number

Optional duration in milliseconds (defaults to config().sleepMs)

Returns

Promise<unknown>

Promise that resolves after the specified delay

Examples

import { sleep } from "@rotorsoft/act";

async function processWithDelay() {
console.log("Starting...");
await sleep(); // Uses config().sleepMs (100ms in dev, 0ms in test)
console.log("Continued after delay");
}
import { sleep } from "@rotorsoft/act";

async function retryWithBackoff(fn: () => Promise<void>, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
await fn();
return;
} catch (error) {
if (i < retries - 1) {
const delay = Math.pow(2, i) * 1000; // Exponential backoff
console.log(`Retrying in ${delay}ms...`);
await sleep(delay);
} else {
throw error;
}
}
}
}
import { sleep } from "@rotorsoft/act";

async function processItems(items: string[]) {
for (const item of items) {
await processItem(item);
await sleep(500); // 500ms between items
}
}
// InMemoryStore uses sleep to simulate async I/O
class InMemoryStore implements Store {
async query(...) {
await sleep(); // Simulate database latency
// ... query logic
}

async commit(...) {
await sleep(); // Simulate write latency
// ... commit logic
}
}
# Set custom default sleep duration via environment variable
SLEEP_MS=50 npm start

# In tests, it's automatically 0
NODE_ENV=test npm test

See

config for sleep duration configuration