sleep-sleep
v1.3.0
Published
Allows you to suspend code execution for a specified time. Or for a random range of time.
Downloads
12
Maintainers
Readme
sleep-sleep 😴
A tiny and simple JavaScript code execution delay library.
0.35 kB! 🚀 and No dependencies 🎉
Under the hood, setTimeout is used, so it's simple and reliable.
Table of contents
Install
Step 1:
npm install sleep-sleep
Step 2:
import sleep from 'sleep-sleep';
Or if you want to use CommonJS:
const sleep = require('sleep-sleep');
Usage
An example of using the sleep function:
import sleep from 'sleep-sleep';
async function demoFunction() {
console.log('3-second delay...');
await sleep(3000); // 3000 ms delay (3 seconds)
console.log('Delay completed.');
}
demoFunction();
You can also use a random delay between the minimum and maximum time value:
import sleep from 'sleep-sleep';
async function demoFunction() {
console.log('Random delay...');
await sleep(1000, 5000); // Random delay between 1 and 5 seconds
console.log('Delay completed after e.g. 3.47 seconds.');
}
demoFunction();
Random delay is very useful for example in Puppeteer and Playwright related projects, where a random pause between actions gives your automation a more human-like 👨🌾 appearance.
API
sleep(minMs: number, maxMs?: number): Promise<void>
minMs
: Minimum number of milliseconds for delay.
maxMs
(optional): The maximum number of milliseconds for the delay. If not specified, the delay will be fixed and equal to minMs