0

My web app currently uses this to kick off notifications retrieval in client-side:

$(document).ready( getNotifications() );

which is great, but i need it to run every XXX seconds, so I've added a setInterval timer at the end of getNotifications(), here:

function getNotifications() {

    //(do stuff)

    //now repeat every X seconds (10000 = 10s)
    setInterval(getNotifications, 30000);
}

problem -- doing this seems to trigger multiple instances of the timer-loop'd function. using an alert() I can see that every timer cycle creates a new instance set to the timer, not an iteration of the same instance as desired.

how can i get a timer/loop for my functionality without multiple instances?

thanks!

mdelvecchio
  • 567
  • 1
  • 5
  • 25

2 Answers2

2

Change setInterval to setTimeout.

setInterval keeps firing every X milliseconds, setTimeout fires once after x milliseconds

And you do not want the () in the document.ready. It is calling getNotifications, not assigning the reference to it.

function getNotifications() {
    window.setTimeout(getNotifications, 30000);
}
$( getNotifications );
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    ah...yes, of course -- setInterval starts a loop of the timer'd function, each running at the interval... but since im self-referring to the function at the end of itself, i only need to call it on via setTimeout, which runs once, and then when it executes itself, it calls itself again, etc... got it, thanks! – mdelvecchio Jun 02 '14 at 23:47
1

Or, how about (keeping the function cleaner by not having the repeat information inside it):

function getNotifications() {

    //(do stuff)
}

$(function() { // this is $(document).ready( in a different form, see http://stackoverflow.com/questions/2662778/what-is-the-difference-between-these-jquery-ready-functions

   getNotiifications(); // call it the first time

   setInterval(getNotifications, 30000); // and every 30 seconds afterwards
}
Guy Schalnat
  • 1,697
  • 15
  • 26