Search code examples
phpjavascriptajax-polling

Trying to call a function every 3 minutes using JavaScript


I have a function that returns an integer (the current reputation score for a user on a community site). That number is often going up or down based on how their comments and submissions are voted on. I'd like to "poll" it every 30 seconds or so to see if it's changed, and if so, update the number that I'm displaying.

In another StackOverflow thread, I found this JavaScript snippet that looked useful:

function listen() {
  $.get("/mylongrequestfile", {}, function(data) {
     $("#mydiv").html(data);
     listen(); // then launch again
  }));
};

Do I just replace /mylongrequestfile with my function? I'm trying that but it's not working so well. How do I use this code, or some other snippet, to grab and display this value every 30 seconds?


Solution

  • You can use

    window.setInterval

    which

    Calls a function repeatedly, with a fixed time delay between each call to that function.

    var intervalID = window.setInterval(yourfunctionname, 300);
    

    This executes in a delay of 300 milliseconds.

    Callback arguments

    setInterval() will pass the number of milliseconds late the callback was called into the callback function, which can confuse it if it expects something else as an argument. To sidestep that problem, use an anonymous function to call your callback.

    The same technique can be used if you need to pass an argument to your callback function, but need it to work in Internet Explorer, which doesn't support sending additional parameters with setInterval().

    var intervalID = setInterval(function() { YourFunction(); }, 300);