Reputation: 440
Running this in terminal node test.js
I was expecting console logs to print runtime close to 2000ms but instead it is well over 5000ms.
Why is that? Is the fetch queuing the requests? Could it be the OS limitation on parallel calls? I dont think the event loop is slowed that much with this simple loop though.
const run = async (i) => {
const start = Date.now();
const abortController = new AbortController();
const timeout = setTimeout(() => {
abortController.abort();
}, 2000);
try {
const v = await (
await fetch("https://slowendpoint.com", {
method: "POST",
body: JSON.stringify([{}]),
signal: abortController.signal,
})
).text();
} catch (e) {
console.error(e);
} finally {
console.log(i, "runtime", Date.now() - start);
clearTimeout(timeout);
}
};
for (let i = 0; i < 10000; i++) {
run(i);
}
Upvotes: 0
Views: 39
Reputation: 2467
To set a timeout for the AbortController, you should create a signal object with a specific timeout. You can do that using:
const signal = AbortSignal.timeout(2000);
Then pass that signal object to the fetch call instead of abortController.signal.
Upvotes: 0