关于 JavaScript 函数的两个问题

Two questions regarding JavaScript function

本文关键字:两个 问题 JavaScript 函数 关于      更新时间:2023-09-26

我对以下函数有两个问题。显然,这是关于聊天的。在函数中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!
});
  1. 很抱歉用问题回答问题,但是openconnectionsearchforcontact的价值是什么?它们似乎不满足条件,因此您的 return 语句未运行。您可以使用 FireBug 或 Chrome 开发者工具验证该值。

  2. getMessages只运行一次,因为您调用它而不是将其传递给setInterval。应该是setInterval(getMessages, 1000);.