There's probably something like this hidden in a corner of the project:
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
It works, yes, but Node.js 16 introduced its own version in timers/promises, so you can just use that directly.
import { setTimeout as sleep } from "node:timers/promises";
The node: prefix is used to clearly tell the toolchain that this is a built-in module, not a package with the same name in node_modules. The as sleep is because calling it setTimeout looks awkward; renaming it makes it clearer.
Basic Usage
async function main() {
await sleep(2000);
console.log("Waited 2 seconds");
}
It works the same as the handwritten version, but eliminates a utility function that didn't need to exist.
It Has One More Parameter Than Your Handwritten Version
The second parameter value is a value that gets passed along when resolving; it can be handy sometimes (and sometimes you never need it—just know it exists).
The third parameter options has a signal property that accepts an AbortController, allowing you to cancel the wait midway—something that would be much more cumbersome to implement in the handwritten version.
Types
TypeScript types for @types/node 18+ are complete, and the generics are correct, so no manual annotations are needed. If you get errors, first check the version; it's likely that @types/node is too old, and npm update @types/node usually fixes it.
What About Old Projects
If you have one, just replace it when you come across it; there's no need to open a dedicated PR for this.