Kevin Danikowski
Kevin Danikowski

Reputation: 5206

console.log on intervals in javascript

I'd like to log a request every 1 or 5 minutes from a heavily requested api, like sampling. I'm curious what this function might look like in javascript? I was thinking some sort of while loop with a setInterval, but not sure how to write it or if it's the best approach?

Update: Based on Afshin's answer

let logNext = true
const minute = 60 * 1000
setInterval(() => {
  logNext = true
}, minute)

const logSample = item => {
  if (logNext) {
    logNext = false
    console.info('item', item)
  }
}

Upvotes: 2

Views: 2230

Answers (1)

Afshin Mobayen Khiabani
Afshin Mobayen Khiabani

Reputation: 1289

You don't need any loops as setInterval is kind of loop itself as it runs for good unless you clear it's handler.

let myinterval = setInterval(function() {
  //Call the api
}, 300000);

if you want to stop the interval:

clearInterval(myinterval);

The API call section will fired up every 5 minutes until you call the clearInterval.

I think you are mistaken setInterval with setTimeout which only fired up once.

Upvotes: 2

Related Questions