How to execute a undefined number of funcA() and funcB() before starting funcC()?

I have a app writed in javascript. To work, I need to download a bunch of files. Since I can have a lot of file wich can be long, I made the download asynchronous:

function download_all(xml, callback){
    var i=0;
    while(i<xml.smil.length)
    {
        download(xml.smil[i]);
        i=i+1;
    }
    i=0;
    while(i<xml.video.length)
    {
        download(xml.video[i]);
        i=i+1;
    }
    callback(xml);
}

My question is: download do have a callback, but since there can be 5 smil and 30 videos, how can I make sure all of the download will be made before the callback of download_all is called?

I thougth of incrementing a variable after each complete download (in the callback) and something like

while(smildlcompleted<xml.smil.length && videodlcompleted<xml.video.length)
{
    sleep(1000);
}

Like I would have do in C, but I can t find a sleep function and it seems to be opposite to the rigth syntax of js/node.js.

Is there a way to wait for all download to complete before the callback?

I did have a look at How to execute a Javascript function only after multiple other functions have completed?, since the problem is quite the same (funcA(), funcB(), and when all done, funcC()), but in my case, funcA() and funcB() can be launched ten or twenty times before I need to do funcC().

I m trying to modify the answer code of the other question to do what I need, but does someone know any easier way?

Try this code.

function download_all(xml, callback){
    var i=0 , no_of_downloads , downloadsCompleted;
    no_of_downloads = xml.smil.length + xml.video.length;

    downloadsCompleted = 0;

    function afterDownload(){
        downloadsCompleted + =1;
        if(downloadsCompleted ===no_of_downloads ) { // all downloads are completed
            callback();    //call the callback here
        } 
    }

    while(i<xml.smil.length)
    {
       download(xml.smil[i],afterDownload);
       i=i+1;
    }
    i=0;
    while(i<xml.video.length)
    {
      download(xml.video[i],afterDownload);
      i=i+1;
    }
 }

Take a look at the Async Github library. It can be used in both node js and browser. You either need async.parallel or async.series.