Search code examples
javascripttimersettimeoutsetinterval

javascript setInterval() collision between the delay and execution time


Is there a way to avoid the conflict between the delay and execution time if the time of execution was longer than the delay using setInterval()?

For example:

setInterval(function(){
  // some code that takes 300 ms to be executed
  // which it's longer than the delay 200 ms
}, 200);

I already found the alternate way, which is to use setTimeout() with recursion to ensure that the delay will start immediately after the function is executed, but my question is about setInterval(), not replacing it with setTimeout()


Solution

  • I'm not sure what is your concern.

    Javascript is always single-threaded that means that in time of execution of the function called by setInterval no other function will be executed and no re-run of setInterval may happen!

    Naturally if in your setInterval called function you use deferred calls you enable the function to finish and be executed again. To protect against such problem you may use a simple semaphore like:

    var inProcessing = false ;
    setInterval(function(){
      // some code that takes 300 ms to be executed
      // which it's longer than the delay 200 ms
         if (!inProcessing){
            inProcessing = true ;
            $http.get(...).then(function(){inProcessing = false;...},
                                function(){inProcessing = false;...});
         }
      }
    }, 200);