setInterval() only running function once

后端 未结 6 1709
遇见更好的自我
遇见更好的自我 2020-11-30 12:07

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          


        
6条回答
  •  执笔经年
    2020-11-30 12:12

    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);
    

提交回复
热议问题