Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: <a href="http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/" rel="noreferrer">http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/</a></p> <p>For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use <code>setInterval()</code>. If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:</p> <pre><code>// Use a named immediately-invoked function expression. (function worker() { $.get('ajax/test.html', function(data) { // Now that we've completed the request schedule the next one. $('.result').html(data); setTimeout(worker, 5000); }); })(); </code></pre> <p>For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:</p> <pre><code>(function worker() { $.ajax({ url: 'ajax/test.html', success: function(data) { $('.result').html(data); }, complete: function() { // Schedule the next request when the current one's complete setTimeout(worker, 5000); } }); })(); </code></pre>
 

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