Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
James Dawson Avatar asked Jan 04 '12 18:01

James Dawson


2 Answers

Change:

setInterval(getMessages(), queryInterval);

To:

setInterval(getMessages, queryInterval);
like image 187
qwertymk Avatar answered Oct 05 '22 05:10

qwertymk


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);
like image 22
Wayne Avatar answered Oct 05 '22 07:10

Wayne