Search code examples
javascriptjquerylong-polling

why cannot recursively call function in jquery?


I am a newbie of JQuery. I want to recursively call 'pullNotification' function as long polling when calling the 'success' function, but my script is called 'pullNotification' function in two times when calling the requests from browser. So please guide me how to solve it. The following are my script. Thanks in advance.

jQuery(function($) {

    var data = [];

    function pullNotification() {
        var params = {};

        new RPC.Call({
            'method': 'users.getJsonUsers',
            'params': params,
            'onSuccess': success     
        });
    };

    function success(result) {
        if (data.length != 0)
        {
            for (var i = 0, item; item = result[i]; i++) {
                for (var k = 0; k < data.length; k++)
                {
                    if (item.userid == data[k])
                    {
                        this.found = true;
                        break;
                    }
                }
                if (this.found)
                {
                    this.data.push(item.userid);
                    $('<tr origclass="even_row" class="even_row">\n\\n\
                                    <td>' + item.userid + '</td>\n\
                                    <td>' + item.alias + '</td>\n\
                                    <td>' + item.surname + '</td>\n\
                                    </tr>').insertAfter('.nilar');
                }
                this.found = false;
            }
        }
        else {
            for (var j = 0; j < result.length; j++)
            {
                data.push(result[j].userid);
            }            
        }

        setTimeout(function() {
                pullNotification();
            }, 1000);
    }

    window.setTimeout(function() {
        pullNotification();
    }, 5000);
});

Solution

  • You only call pullNotification onSuccess -- is there an onFailure? It might be easier (and easier to reason about) if you did

    window.setTimeout(function() {
      window.setInterval(function() {
        pullNotification();
      }, 1000);
    }, 5000);
    

    and then removed the setTimeout from success(result) { ... }

    That way, you will call pullNotification once per second regardless of what's happening. It does have the potential to continue to ping your server if requests take longer than 1 second though.