Junior — Middle
How can you implement a wait or delay mechanism when calling an API?
sobes.tech AI
Answer from AI
To implement a wait or delay mechanism when calling an API, several approaches can be used:
-
Explicit delay (sleep) — using functions that pause execution for a specified time. For example, in JavaScript, this is
setTimeoutorawait new Promise(resolve => setTimeout(resolve, ms)). -
Polling — periodically querying the API with delays between requests until the desired result is obtained.
-
Using asynchronous calls with timeout — for example, in Python with
asyncio.sleepor setting a timeout on the request.
Example in JavaScript with a delay before calling the API:
async function callApiWithDelay() {
await new Promise(resolve => setTimeout(resolve, 2000)); // 2-second delay
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
This approach allows controlling the time between requests, which is useful for limiting server load or adhering to API rate limits.