I have two questions regarding the following function. Obviously, it is about a chat. In the function chat() different functions are called, one to establish a connection, one to search for someone to chat with (randomly), and one to get messages every second.
function chat()
{
//Open connection
var openconnection=openConnection();
//Stop function if connection could not be established
if(openconnection==false) return;
//Search for someone to chat with
searchforcontact=searchForContact();
if(searchforcontact==false) return;
//Constantly get messages
setTimeout(function(){
setInterval(getMessages(),1000);
},2000);
}
function openConnection() {
//Establish connection to php script
$.ajax({
type: 'POST',
url: 'action/chat/openconnection.php',
success: function(connection) {
//Let user know that someone to chat with is searched for
$('#chatTextDiv').append('bla');
//Return that the connection was successfull
return true;
}
}).error(function() {
//Let user know that a connection could not be established
$('#chatTextDiv').append('bla');
//Return false
return false;
});
}
Here are my questions:
1: I use return to stop the function chat() if, e.g., a connection could not be established. However the functions goes on to searchForContact(), and even if that fails, still goes on. How come?
2: The function getMessages() only runs once, I wonder why? FYI, I use the timeout for usability.
Most likely
openConnection()doesn’t return false. Since synchronous API are very uncommon and not really useable from within JavaScript, I am pretty sure, thatopenConnectiondoes not work the way you use it. Please provide more information on theopenConnectionfunction.Also, instead of passing the
getMessagesfunction to the call tosetInterval, you invokegetMessagesand pass whatever it returns tosetInterval. This is most likely not what you want. You should change that call to the following:You should really read up on how AJAX and asynchronous APIs in general work. To give you a head-start here is an update to your code that should demonstrate what you’re doing wrong: