Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a callback passed to the setInterval be fired even if the previos one didn't finish its work yet

Will a callback passed to the setInterval function be fired even if the previous one (fired by the same setInterval) didn't finish its work yet? If so, what can I do to workaround this behavior? Should I use my own boolean flag (like inProcess) or call setTimeout every time instead of setInterval?

like image 369
FrozenHeart Avatar asked Feb 11 '16 14:02

FrozenHeart


1 Answers

I would suggest using setTimeout.

I had similar problem and where I had to poll server for certain data every 3s till I receive data or a threshold is reached. I had written something like this:

function getData(){
  $.post(url,data, function(res){
    if((res.error || res.data.length === 0) && pollCount < 20 ){
      initTimeout();
    }
    else{
      processData(res.data);
    }
  })
}

function initTimeout(){
  var delay = 3000;
  setTimeout(function(){ getData(); },delay)
}

initTimeout();

Benefit of this approach is,

  • First, you do not have to make interval/timeout variable as global/in parent scope, so you can clear on success.
  • Second, initTimeout can be made generic like
function initTimeout(callback, delay) {
  setTimeout(function() {
    callback();
  }, delay);
}
like image 100
Rajesh Avatar answered Sep 26 '22 14:09

Rajesh