Mustapha George
Mustapha George

Reputation: 2527

javascript - multiple settimeouts in loop

I want to read a file, do some stuff, check action mode.

If mode = STOP then delay processing until mode != STOP, otherwise repeat entire process.

I want it to keep delaying until mode changes.

The code below results in an infinite loop & browser crash:

function fnIterateGeocode(addressVariations) {

    // read a file & do some stuff  

    // check for delay
    fnDelay();

   // if not end of file then Iterate
   if (nextRecord.EOF != 'Y') {
        setTimeout(function(){                      
            fnIterateGeocode(addressVariations);                        
        }
        , 5000);
    }


    // if mode = STOP, then delay for 5 seconds and check again     

    function fnDelay(){
        if(mode == 'STOP'){
                setTimeout(function(){                                                      
                }
                , 5000);
                fnDelay();
        }
        return;
    }           

    return;
}

Upvotes: 0

Views: 194

Answers (2)

beeglebug
beeglebug

Reputation: 3552

I don't think you fully understand asynchronous code.

There is no way to 'delay' javascript in the way you are trying (like wait, or sleep in other languages). The call to setTimeout does not halt execution at that point for 5 seconds.

Try thinking of setTimeout as a request to put the passed in function into a queue to be called at some point in the future. Once done, the script will immediately proceed to the next line of code as with any other function call.

In your example, something like the following would make more sense:

function fnDelay(){
    if(mode != 'STOP'){ fnIterateGeocode(); }
    else { setTimeout(fnDelay,5000);
}

This will call itself every 5 seconds as long as mode == 'STOP', as soon as it doesn't, it will call fnIterateGeocode.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075567

You've put the call back to fnDelay in the wrong place:

function fnDelay(){
    if(mode == 'STOP'){
            setTimeout(function(){
                // It should be here
            }
            , 5000);
            fnDelay(); // Not here
    }
    return;
}

The way your code is current written is indeed an infinite loop (well, it would be if you didn't run out of stack space), because fnDelay always calls itself immediately.

Upvotes: 2

Related Questions