I need to run asynchronous JavaScript functions in a loop. I need this to test the performance of my web application.
SpeedTest.asyncLoop = function(iterations, func, callback)
{
var index = 1;
var done = false;
var loop = {
next: function()
{
if (done)
{
return;
}
if (index <= iterations)
{
index++;
func(loop);
}
else
{
done = true;
callback();
}
},
iteration: function()
{
return index - 1;
},
stop: function()
{
done = true;
callback();
}
};
loop.next();
return loop;
};
//Call it here
SpeedTest.asyncLoop(10,
function(loop) {
MyAsyncFunction(function() {
Common.log(loop.iteration());
loop.next();
});
},
function(){
Common.log( 'Test done');
}
);
//Here is the function that will be called 10 times in a loop
function MyAsyncFunction(callback){
//Call here
if (typeof callback === "function")
{
callback();
}
}