6

I have an array which is filled asynchronous and contains 28 items. I want to wait until the array is filled with all items.

function checkIfFinished(){
    return(Results.length >= 28);
}

var isfinished = false;
while(isfinished){
    if(checkIfFinished()){
        returnResults();
        isfinished = true;
    }
    else
        //Wait 100ms 
}

Well, but in Javascript there is no wait function! I tried it with setTimeout, but I don't know how to insert it... I just get errors with too much recursion and stuff :D

Thank you!

Weedjo
  • 335
  • 1
  • 6
  • 17
  • 3
    Are you filling the array yourself? If so, might want to use a custom event to fire/listen to when done filling. – pimvdb Nov 25 '11 at 10:43
  • There is a simple rule. One does not write synchronous (blocking) JavaScript. – Tomalak Nov 25 '11 at 10:44

2 Answers2

13

Try:

var timeout = setInterval(function() {
    if(checkIfFinished()) {
        clearInterval(timeout); 
        isFinished = true;
    }
}, 100);

This will call your check-function every 100 ms until checkIfFinished() gives true back to you.

Guga Nemsitsveridze
  • 721
  • 2
  • 7
  • 27
lfxgroove
  • 3,778
  • 2
  • 23
  • 33
3

If you're using jQuery 1.5+, this sounds like a perfect opportunity to use deferred objects and promises in your code. I'm assuming that you're using AJAX calls to populate your array.

In a nutshell, something like this should work for you:

$(function() {

    var $ajaxcalls = [],
        myArray = [];

    // set up all the ajax calls that will populate my array
    for(var i=0; i < 28; i++) {
        $ajaxcalls[i] = $.ajax({
            url : 'http://your.domain.com/blah',
            data : i
        }).success(function(m) {
            myArray.push(m);
        });
    }

    // this will setup the promise --- 
    // what will run when all 28 AJAX calls complete?
    $.when.apply(null, $ajaxcalls).then(function() {
        returnResults();
    });

});

I've written about this some time back as well. I really think it's a nifty feature / concept that can be really powerful when used correctly. Javascript timers and schedules should work as well, but they can be unwieldy and may result in a bit of wait time before the actual completing logic fires.

Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66