I’m working on a JavaScript project where I need to delay a fetch request. However, due to some project constraints, I can’t use setTimeout
or setInterval
. I’m aware that these are the usual methods for delaying execution in JavaScript, but I need an alternative approach.
I’ve considered using Promise or busy-waiting with a while loop, but these methods are not ideal as they either still use setTimeout
under the hood or block the execution of other code.
Here’s a basic example of the kind of operation I’m trying to perform:
async function delayedFetch(url, delayTime) {
// Need to delay here without using setTimeout or setInterval
const response = await fetch(url);
const data = await response.json();
return data;
}
delayedFetch('https://api.example.com/data', 2000)
.then(data => console.log(data));
Sujal Shah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1