What is the best/recommended manner in which to insert a ‘pause’ with each enumeration over a set of elements using the jQuery ‘.each()’?
$( '.someClass' ).each( function() {
$( this ).trigger( 'click' ); //fire some request that appends a new div on the body
//wait for div to be appended to the DOM. perhaps use the pause here
//execute code once the div has been appended
});
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:
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:
confirm()or something while processing each item, the next item will be processed 5 seconds from the time that the user closes the dialog.Here’s a function you can use that encapsulates this functionality:
Called like:
See the updated fiddle.