SetInterval () only works the function once

I want to periodically request a PHP script for new posts. For this, I use the setInterval () and AJAX functions.

$(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 only see a tick. I made sure that the console does not ignore the logs of the same lines anymore, therefore, if the code worked correctly, it should show a β€œtick” in the console every second.

Does anyone know what could be wrong here?

+6
source share
4 answers

Edit:

 setInterval(getMessages(), queryInterval); 

To:

 setInterval(getMessages, queryInterval); 
+23
source

In fact, setInterval does not work getMessages at all (not even once). setInterval expects a reference to the function, but you immediately execute the getMessages function and pass its return value to setInterval (which is undefined ). This is what parens do after getMessage .

Pass the link to setInterval as follows:

 setInterval(getMessages, queryInterval); 

If this is the only place that getMessages used, you can also write it like this:

 setInterval(function() { console.log("tick"); }, queryInterval); 
+9
source

Remove () after getMessage

+1
source

This call is getMessages , not a schedule. Remove the brackets.

 setInterval(getMessages(), queryInterval); setInterval(getMessages, queryInterval); 
+1
source

Source: https://habr.com/ru/post/905126/


All Articles