setInterval() only running function once
I want to periodically query a PHP script for new messages. To do so, I'm using the setInterval() function and AJAX.
$(document).ready(function(){
var queryInterval = 1000; /* How fast we query for new messages */
setInterval(getMessages(), queryInterval);
function getMessages() {
console.log("tick");
}
});
However, when I look at the Javascript console, I'm only seeing "tick" once. I've made sure that the console doesn't ignore any more logs of the same strings, so if the code was working properly it should show "tick" in the console every second.
Anyone know what could be going wrong here?
Change:
setInterval(getMessages(), queryInterval);
To:
setInterval(getMessages, queryInterval);
Actually, setInterval
isn't running getMessages
at all (not even once). setInterval
expects a reference to a function, but you're executing the getMessages
function immediately and passing its return value to setInterval
(which is undefined
). That's what the parens after getMessage
do.
Pass a reference to setInterval
like this:
setInterval(getMessages, queryInterval);
If this is the only place that getMessages
is used, then you could also write it like this:
setInterval(function() {
console.log("tick");
}, queryInterval);