Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Fetch data from an API in regular interval in NodeJS

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()
question from:https://stackoverflow.com/questions/65882633/fetch-data-from-an-api-in-regular-interval-in-nodejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...