javascript / intermediate
Snippet
Enforcing Timeouts with AbortSignal.timeout
Modern Node.js versions provide a shorthand for creating time-based abort signals. This prevents async operations from hanging indefinitely and consuming resources.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
async function fetchData(url) {try {// Automatically aborts after 5000msconst signal = AbortSignal.timeout(5000);const response = await fetch(url, { signal });return await response.json();} catch (err) {if (err.name === 'AbortError') {console.error('Request timed out');}}}
nodejs
Breakdown
1
AbortSignal.timeout(5000)
Creates a signal that automatically triggers an abort event after 5 seconds.
2
fetch(url, { signal })
Passes the signal to the fetch API to link the request lifecycle to the timeout.