1

I want to fetch data from an API in regular interval. I wrote a script which is fetching data successfully but how to repeat this step for infinite time, so that I can fetch data in regular interval.

I want to fetch data in the interval of 1sec, what should I do?

const fetch = require('node-fetch')
const time = new Date()

function saveData(metrics) {
  console.log(time.getSeconds())
  console.log(metrics)
  console.log(time.getSeconds())
}

const getData = () => {
  fetch('http://example.com/api/v1')
    .then(response => response.json())
    .then(saveData)
    .catch(err => console.error(err))
}

getData()
Andre
  • 1,042
  • 12
  • 20
Harsh
  • 45
  • 5
  • 2
    Does this answer your question? [Run JavaScript function at regular time interval](https://stackoverflow.com/questions/18070659/run-javascript-function-at-regular-time-interval) – Jorge Fuentes González Jan 25 '21 at 10:10
  • Just a side note: maybe I misunderstood your aim but it looks to me that it does not make a lot of sens to declare `const time = new Date()` outside the `saveData()` function, if it has to be executed at regular intervals. – secan Jan 25 '21 at 10:16

1 Answers1

3

Just use it like this

const interval = setInterval(() => {
  getData();
}, 1000);

If you want to avoid making wrapper callback like above, you can just pass getData as a callback, which setInterval will call after each specified interval time i.e 1 second here

const interval = setInterval(getData, 1000);
mss
  • 1,423
  • 2
  • 9
  • 18
  • 1
    Seems to be a nice solution for this problem. A shorter solution might be `const interval = setInterval(getData, 1000)` but I don't think you get any benefit from using the shorter version of this code. I just wanted to mention that. – Andre Jan 25 '21 at 10:22
  • 1
    @Nope, you are right, we can just pass the getData as a callback to the setInterval, which it will call after each specified interval. I have just wrapped getData with my own callback, wanted to make it more readable to OP – mss Jan 25 '21 at 10:24
  • 1
    @Nope, added your suggestion too – mss Jan 25 '21 at 10:28
  • Are both solutions asynchronous (because of the callbacks)? So I could have several functions set up like this in the same file going off at different intervals? – user2066480 Jan 23 '22 at 01:04