How to Call an API Every 5 Seconds Using JavaScript

Learn how to make API calls every 5 seconds in JavaScript with a simple example using setInterval.

460 views

To make an API call every 5 seconds in JavaScript, use the `setInterval` function. Here’s an example: ```javascript function fetchData() { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); } setInterval(fetchData, 5000); ``` This code repeatedly calls the API every 5000 milliseconds, ensuring you get updated data at regular intervals.

FAQs & Answers

  1. How does setInterval work in JavaScript? setInterval executes a specified function at defined intervals, measured in milliseconds.
  2. Can I stop the API calls made with setInterval? Yes, you can use clearInterval with the interval ID returned by setInterval to stop the API calls.
  3. What is the best practice for making API calls in JavaScript? Always handle errors gracefully and consider using async functions with try/catch for better readability and manageability.
  4. Is fetch supported in all browsers? Fetch is supported in all modern browsers. For older ones, you might need to use a polyfill.