Technically, you can't do this as you have modeled in your code, since JavaScript is single-threaded, and usually runs on the browser (or tab) UI thread -- any sleep/delay will block the browser from redrawing the page and will also prevent user interaction with the page.
You need to arrange for the browser to invoke your code periodically. Something like this will do the trick:
var objects = $.makeArray($( '.someClass' ));
var callback;
callback = function() {
var item = objects.shift();
// Do something with item.
if (objects.length != 0) {
setTimeout(callback, 5000);
}
}
setTimeout(callback, 5000);
See an example.
This solution assumes that you want each item to be processed 5 seconds from the time that the last item finished processing. This means that:
- If you do
confirm()
or something while processing each item, the next item will be processed 5 seconds from the time that the user closes the dialog.
- The total execution time will be (5000N + T) where N is the number of items in the initial list, and T is the total time it takes to process each item.
Here's a function you can use that encapsulates this functionality:
jQuery.eachWithDelay = function(sequence, delay, callback) {
var objects = jQuery.makeArray(sequence);
if (objects.length == 0) {
return;
}
var f;
f = function() {
var item = objects.shift();
if (callback(item) && objects.length != 0) {
setTimeout(f, delay);
}
};
setTimeout(f, delay);
};
Called like:
$.eachWithDelay($('.someClass'), 5000, function(item) {
// Do something with item
return true; // Return true to continue iterating, or false to stop.
});
See the updated fiddle.