Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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.</p> <p>You need to arrange for the browser to invoke your code periodically. Something like this will do the trick:</p> <pre><code>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); </code></pre> <p>See <a href="http://jsfiddle.net/zmzsA/1/" rel="nofollow">an example</a>.</p> <p>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:</p> <ol> <li>If you do <code>confirm()</code> or something while processing each item, the next item will be processed 5 seconds from the time that the user closes the dialog.</li> <li>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.</li> </ol> <hr> <p>Here's a function you can use that encapsulates this functionality:</p> <pre><code>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) &amp;&amp; objects.length != 0) { setTimeout(f, delay); } }; setTimeout(f, delay); }; </code></pre> <p>Called like:</p> <pre><code>$.eachWithDelay($('.someClass'), 5000, function(item) { // Do something with item return true; // Return true to continue iterating, or false to stop. }); </code></pre> <p>See the <a href="http://jsfiddle.net/YB7Ha/" rel="nofollow">updated fiddle</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload