Wait for callback before continue for loop

Assuming this is your array

var list = ['one','two','three'];

You can try using this loop / callback approach

var x = 0;
var loopArray = function(arr) {
    customAlert(arr[x],function(){
        // set x to next item
        x++;

        // any more items in array? continue loop
        if(x < arr.length) {
            loopArray(arr);   
        }
    }); 
}

function customAlert(msg,callback) {
    // code to show your custom alert
    // in this case its just a console log
    console.log(msg);

    // do callback when ready
    callback();
}

Usage:

// start 'loop'
loopArray(list);

JSFiddle here: http://jsfiddle.net/D9AXp/

Leave a Comment