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(";, {
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);
}
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", {
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);
}
Share
Improve this question
edited yesterday
VLAZ
29.1k9 gold badges62 silver badges84 bronze badges
asked yesterday
Nischit PradhanNischit Pradhan
4406 silver badges19 bronze badges
1 Answer
Reset to default 0To 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.