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() 
2
  • 2
    Does this answer your question? Run JavaScript function at regular time interval Commented Jan 25, 2021 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. Commented Jan 25, 2021 at 10:16

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@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
@Nope, added your suggestion too
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.