I meet a js interview question like this:
There is an array, which items are all functions, these function all need ajax call. Write a function to detect when all functions return result, and return these result.
I didn't see original title, so I can't supply more information, I know it need use callback function to count resolve the problem, but I have no idea how to write code because I'm not familiar with js, does anyone can give me some idea with code fragment?
Thanks!
Asked
Active
Viewed 51 times
-2

Rambo Li
- 307
- 1
- 3
- 16
-
Check this: http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – cch Feb 24 '15 at 04:39
1 Answers
0
Please check following code.. you've to define one counter and one function which will be called whenever ajax call completed in a function it will update the counter and check that all functions completed ajax call or not.. if counter = array length than it means all functions completed their ajax call irrespective of their order. I can't provide you the jsfiddle link because I can't mention url in this code because cross domain ajax url doesn't work so you have to execute this script on your domain.
var counter = 0;
function checkCounter()
{
if (counter == arr.length)
alert ("all functions executed from array");
}
var arr = [
function() { $.ajax({ url: ""}).done(function() { counter++; checkCounter() }); },
function() { $.ajax({ url: ""}).done(function() { counter++; checkCounter() }); }
];
for (var i=0; i<arr.length; i++)
{
arr[i]();
}

razahassank
- 195
- 8