I'm running a setTimeout, recursively, so I only want to call the API one time per minute.
Here is my code:
;(async function ticker (minutes) {
try {
const res = await coingecko.global()
const { market_cap_percentage } = res.data.data
dominance = { btc: market_cap_percentage.btc, eth: market_cap_percentage.eth }
console.log({ dominance })
} catch (ex) {
console.log(ex.message)
} finally {
setTimeout(ticker, minutes * 60 * 1000)
}
})(1)
The problem is:
- When I start my server, it calls the API immediately
- It takes one minute to make a second call (expected behaviour)
- After the second call, it starts calling the API sequentially, without a timeout
setInterval
? – Rohit Kashyap Jan 24 at 20:06setInterval
does a different job. It calls a function afterinterval
milliseconds, no matter what. Instead, OP probably wanted the timer to start after the request succeeded or got an error – Cristian Traìna Jan 24 at 20:11setInterval
to call the API every one minute. If you need further control oversetInterval
, clear intervals based on your conditions. Closures anyone? And, OP is using thesetTimeout
insidefinally
. What difference would it make exactly? @CristianTraìna – Rohit Kashyap Jan 24 at 20:14coingecko.global()
takes 3 seconds to fulfill, in the OP approach the interval is then 63 seconds, instead withsetInterval
it would be 60 seconds – Cristian Traìna Jan 24 at 20:21