Timeout values are not very reliable because they depend on the available computing power. What takes 10 seconds on a fast PC may take 30 seconds on a slightly slower or busy PC. Nevertheless, timeouts have a right to exist because they are easy to implement. In the following, I would like to show you how you can add a timeout in your npm scripts for your build pipeline.
1. Sleep
The easiest way to add a timeout is to use the Linux sleep command. Simply pass it the specified number of seconds as an argument and use it in your "scripts" section of your "package.json" file:
"scripts": {
"server1": "node ./src/server1.js",
"server2": "node ./src/server2.js",
"timeout": "sleep 5",
"start": "npm run server1 && npm run timeout && npm run server2"
}
⚠️ This only works on Linux operating systems and macOS! For Windows you would have to use the Windows Subsystem for Linux or one of the following two options because there is no sleep
command on windows.
2. Delay
Sindre Sorhus, who actively maintains 1164 npm packages at the time of this writing (🤯), mimicked the behaviour of sleep
with JavaScript in his delay-cli package. It can be installed as development dependency and used across platforms:
"devDependencies": {
"delay-cli": "2.0.0"
},
"scripts": {
"server1": "node ./src/server1.js",
"server2": "node ./src/server2.js",
"timeout": "delay 5",
"start": "npm run server1 && npm run timeout && npm run server2"
}
3. setTimeout
Who wants to cover most operating systems (macOS, Linux & Windows) without installing additional dependencies can use setTimeout
. Node.js is able to run inline JavaScript code using the -e
(--eval) command-line option.
Node.js v16 provides Promises-based timer functions that are easy to use:
"scripts": {
"server1": "node ./src/server1.js",
"server2": "node ./src/server2.js",
"timeout": "node -e \"require('node:timers/promises').setTimeout(5_000)\"",
"start": "npm run server1 && npm run timeout && npm run server2"
}
☝️ Note: You can prefix Node.js builtin modules with node:
to differentiate them from third-party packages.
Get connected 🔗
Please follow me on Twitter or subscribe to my YouTube channel if you liked this post. I would love to hear from you what you are building. 🙂 Best, Benny
Top comments (0)