Loop through array of div ids, and refresh those divs every x seconds

Mar 13, 2012   //   by phpfreelancer.biz   //   Blog, Jquery Tutorial  //  No Comments

I have 4 divs:

<div id='blue'></div>
<div id='refresh12'></div>
<div id='red'></div>
<div id='refresh23'></div>

i am putting every div on my page that begins with ‘refresh’ into an array like this:

var divs = $('div[id^="refresh"]');

Now, what I want to do, is refresh the divs in the array every 5 seconds. I know I need to use SetInterval, but I’m not sure how to start the loop. Also, the divs aren’t pulling content from another page, it’s from the same page, just dynamic data that needs to be refresh every 5 seconds.

You can use setTimeout() calls like this to achieve what you want:

var divs = $('div[id^="refresh"]');

setTimeout(function refreshThem () {

    //code to refresh your divs
    divs.xy();

    setTimeout(refreshThem, 5000);

}, 5000);

or if you want the first refresh to run at once:

(function refreshThem () {

    //code to refresh your divs
    divs.xy();

    setTimeout(refreshThem, 5000);

})();

Basically when the refresh is finished, a new timeout is set up to run the same code again in 5 seconds.

Leave a comment

Share This Post

RSS Wordpress News