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
?
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,
interval/timeout
variable as global/in parent scope, so you can clear on success.initTimeout
can be made generic likefunction initTimeout(callback, delay) {
setTimeout(function() {
callback();
}, delay);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With