views:

467

answers:

3

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 javscript 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?

A: 

window.setInterval method is what you are looking for.

Vilx-
+4  A: 

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);
rahul
What do I do with the "var" at the front? Right now I'm using <?php print myfunction(); ?>It sounds like I could use <?php $intervalID = setInterval(function() { myfunction(); }, 300); print $intervalID; ?>Would that work?
bflora
var is used for variable declaration in javascript.
rahul
To avoid anybody relying on it, it's worth mentioning that the "lateness" parameter is only supported on Mozilla (it's actually left over from Netscape browsers of the 1990s), and also tends to have values that drift away from reality over time. See https://bugzilla.mozilla.org/show_bug.cgi?id=512259 where Brendan Eich says it's time to get rid of it, and https://bugzilla.mozilla.org/show_bug.cgi?id=394769 where doing so is discussed at more length, and the potential inaccuracy of the value is mentioned. Most importantly, don't use it :-)
NickFitz
A: 
var listener = function () {
$.get("http://www.domain.tld/script/", {}, function(data) {
    $("#mydiv").html(data);
}));
};

var interval = setInterval(listener, 30000);
code_burgar