making asynchronous calls with jquery
I have a function called checkStatus(x)
where x is Id. How can I call this function n times asynchronously ? Without being dependent one on another to completed and for another to start?
I'm using jquery
EDIT:
I'm not sure if I used the correct term, but here is what I want. I have a list of ID's and I iterate trough a list, I want to execute this function for each ID.
But I don't want to wait for one id to finnish, an开发者_高级运维d then to execute this function on another id. Is it possible to execute this function at the same time?
Javascript engines are single-threaded, meaning that only one piece of code is ever executing at once. Asynchronous features (AJAX, timeouts/intervals) cause different blocks of code to run in sequence, not in parallel (i.e. you'll never get any use out of multiple processor cores in Javascript).
The simplest way to produce asynchronous (non-blocking) code is using setTimeout
(I strongly discourage using setInterval
), as others have suggested, but there is no performance benefit to doing so. This simply ensures that your browser won't "hang" during slow JS computations, by allowing the browser's other tasks (such as page repainting and user input) the opportunity to run. It won't actually increase the speed of those computations (in fact, it slightly slows them, due to the small additional overhead of the timeouts).
It is possible to create separate threads in Javascript using web workers, but their capabilities are limited (for example, they cannot alter the DOM) and they are not yet supported by IE.
An example of a long-running, non-blocking task using "recursive" setTimeout
calls:
function getStarted(elements) {
// this function must be inside the outer function
// so that `i` (below) can be accessed via a closure
function processElement() {
// do work on elements[i] here
// or pass it to another function
// this continues only if we haven't hit the end of the array,
// like the second and third clauses of a `for` loop
if (++i < elements.length) {
setTimeout(processElement, 0);
}
}
// don't bother with empty arrays
if (elements.length) {
// the same `i` is used each time processElement runs
// and acts just like a `for` loop index
var i = 0;
// optional: make a copy of the array so that it
// doesn't get modified while we're working
elements = elements.slice();
// even a zero-millisecond "delay" gives the browser the
// opportunity to run other code
setTimeout(processElement, 0);
}
}
Use the setTimeout
or setInterval
functions.
setTimeout(function(){checkStatus(x);}, 100);
setTimeout(function(){checkStatus(x);}, 200);
setTimeout(function(){checkStatus(x);}, 300);
精彩评论