我对以下函数有两个问题。显然,这是一场聊天。在函数 chat()
中,调用了不同的函数,一个用于建立连接,一个用于搜索要聊天的人(随机),一个用于每秒获取消息。
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;
});
}
这是我的问题:
1:如果无法建立连接,我会使用 return 来停止函数 chat()
。然而,这些函数会继续执行 searchForContact()
,即使失败,仍然会继续。怎么会这样?
2:函数getMessages()
只运行一次,我想知道为什么?仅供引用,我使用超时是为了提高可用性。
最佳答案
最有可能 openConnection()
不返回 false。由于同步 API 非常罕见,并且在 JavaScript 中并不真正可用,因此我非常确定 openConnection
不按照您使用的方式工作。请提供更多信息openConnection
功能。
此外,不要传递 getMessages
函数调用 setInterval
,您调用 getMessages
并将其返回的任何内容传递给 setInterval
。这很可能不是您想要的。您应该将该调用更改为以下内容:
setTimeout(function(){
setInterval(getMessages,1000);
},2000);
您应该认真阅读 AJAX 和异步 API 的一般工作原理。为了给您一个良好的开端,我们对您的代码进行了更新,该更新应该可以演示您做错了什么:
function openConnection(success, error) {
//Establish connection to php script
$.ajax({
type: 'POST',
url: 'action/chat/openconnection.php',
success: success
}).error(error||function () {});
}
function chat(ready) {
//Open connection
openConnection(function () {
// If this function is called, then the connection is established
//Search for someone to chat with
searchforcontact=searchForContact();
if(searchforcontact==false) return;
// I STRONGLY SUPPOSE searchForContact is also an asynchronous API!
//Constantly get messages
setTimeout(function(){
setInterval(getMessages,1000);
ready();
},2000);
}, function () {
// when this function is called, something went wrong.
});
}
chat(function () {
// when this function is called, chat is ready to be used!
});
关于javascript - 关于JavaScript函数的两个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10432208/