Published on

Adding a Timeout to a Promise in JavaScript

Authors

Sometimes we might want to add a timeout for a Promise in JavaScript.

For such cases, p-timeout by Sindre Sorhus might be a good choice for us.

With this package, we can add timeout with flexible configuration support as well. For example, we can throw a custom error message, fallback function, abort signal support, etc

Dependency

npm install p-timeout

Snippet

// import Promise-based version of setTimeout
import {setTimeout} from 'node:timers/promises'; 
import pTimeout from 'p-timeout';

const delayedPromise = setTimeout(3000); // 3 secs

await pTimeout(delayedPromise, {
	milliseconds: 4000, // 4 secs
});
// 👉 [TimeoutError: Promise timed out after 4000 milliseconds]

Happy Promise timeouts!