1

I have a synchronous function inside setInterval() where I have set the timeout to 1 second. At times, the synchronous function inside setInterval() takes 30+ seconds to execute. Meaning, the function defined inside setInterval() is taking more than timeout set. Recently, I have been facing lot of issues inside this function which im not able to track.

Can anyone tell me if it is a problem when function inside setInterval takes more than the timeout? Or if theres any other ideal way to keep on calling a function whose execution time is unpredictable?

Sample Code:

myFunction = async()=>{
 // Some synchronous external API calls which takes 30+ seconds to execute
}    
setInterval(myFunction,1000)
Tony Mathew
  • 880
  • 1
  • 12
  • 35
  • 2
    can you please show the code, you are having trouble with? – Argee Aug 06 '20 at 08:48
  • 1
    AFAIK, setInterval is NOT guaranteed to run at the exact timing set. It will wait AT LEAST the set timing before it executes. It depends on how many tasks are running. https://stackoverflow.com/questions/8173580/setinterval-timing-slowly-drifts-away-from-staying-accurate – codemax Aug 06 '20 at 08:50
  • Looking at myFunc(), it will obviously take 30+ seconds for setInterval to execute. It needs to wait for the micro task (the network call) to complete. Hence, the 1 second interval set is meaningless. – codemax Aug 06 '20 at 08:56
  • @Argee I have updated my question with sample code. The original code Im trying to execute is huge, which is why I have posted a similar minimalist code. Hope it helps – Tony Mathew Aug 06 '20 at 08:56
  • 1
    `myFunction` is *not* synchronous. – deceze Aug 06 '20 at 08:57
  • You probably want to `setTimeout(myFunction, 1000)` *at the end of `myFunction`*. Meaning, you let it call itself again after a timeout after it has finished executing. – deceze Aug 06 '20 at 08:59

0 Answers0