gjw80
gjw80

Reputation: 1078

Using setInterval with asynch functions that could take longer than the interval time

Is there a way to keep your asynch functions somewhat in order using setInterval? For instance, if you're doing some kind of IO connection and it takes longer than the interval time you set you get things a little off. I could increase the interval time to something that hopefully would cover it, but that's not sure fire enough.

The code looks like this:

var sqlID = setInterval(function(){
    console.log('Attempting to reconnect to sql...');
    dbHandler.connectSQL(sql, connStr, function(sqlconnect){
        conn = sqlconnect;
        if (conn != false){
            clearInterval(sqlID);
        }
    });
}, 10000);

Upvotes: 0

Views: 320

Answers (1)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

If you want them queued, wihtout Promises/Deferreds you can do:

function tryToConnectIn10Seconds(){
   setTimeout(function(){
     console.log('Attempting to reconnect to sql...');
     dbHandler.connectSQL(sql, connStr, function(sqlconnect){
        conn = sqlconnect;
        if (conn != false){
            //Done. Do something with conn
        }else{
            tryToConnectIn10Seconds();
        }
     });
   }, 10000);
}

Cheers

Upvotes: 1

Related Questions