Sobes.tech
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:

  1. Explicit delay (sleep) — using functions that pause execution for a specified time. For example, in JavaScript, this is setTimeout or await new Promise(resolve => setTimeout(resolve, ms)).

  2. Polling — periodically querying the API with delays between requests until the desired result is obtained.

  3. Using asynchronous calls with timeout — for example, in Python with asyncio.sleep or 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.

How can you implement a wait or delay mechanism when… - sobes.tech