Hi,
By marking the ajax requests synchronous, you're basically bringing UI
updates to a screeching halt. :-) Rather than doing a synchronous
loop, how 'bout doing a chained asynchronous loop? E.g., suppose we
have a list (perhaps an Element array from $$) and we want to do a
call to the server for each element, and update its contents based on
the result. Rather than this (pseudo-code):
list.each(function(elm) {
new Ajax.Request(some_url + '?id=' +
elm.id, {
asynchronous: false,
onSuccess: function(xport) {
elm.update(...content derived from xport response...);
},
onFailure: function(xport) {
elm.update(ERROR_MESSAGE);
},
onException: function(req, ex) {
elm.update(EXCEPTION_ERROR_MESSAGE);
loopIteration(list, index + 1);
}
});
});
How 'bout this pseudo-code:
loopIteration(list, 0);
function loopIteration(list, index) {
var elm;
if (index < list.length) {
elm = list[index];
new Ajax.Request(some_url + '?id=' +
elm.id, {
onSuccess: function(xport) {
elm.update(...content derived from xport
response...);
loopIteration(list, index + 1);
},
onFailure: function(xport) {
elm.update(ERROR_MESSAGE);
loopIteration(list, index + 1);
},
onException: function(req, ex) {
elm.update(EXCEPTION_ERROR_MESSAGE);
loopIteration(list, index + 1);
}
});
}
}
You see how the completion of each asynchronous call triggers the
next; the loop counter and list are maintained in the execution
contexts of the various closures. I did the chaining calls to
loopIteration() separately in the above (rather than in onComplete) in
case failures or exceptions should not continue the loop. If there
are aspects of the page that should be disabled while the loop is
running, you can handle that with a modal flag and disabling relevant
controls during the course of the loop.
There are several advantages to a chained asynchronous loop rather
than a synchronous loop. One of the biggest is that browser can
continue to respond to UI events while the calls are outstanding. Not
only would that solve your painting problem, but it opens up other UI
options, like having a Stop button (with a synchronous loop you could
have it, but the user couldn't click it), or allowing the user to
scroll around in the page while the loop is running, etc. With
synchronous calls, many browsers completely lock up the UI during the
call.
HTH,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available