views:

110

answers:

1

I'm trying to make long poll ajax calls, back to back. The problem with the current way I'm doing it is that I make each successive call from the callback function of the previous call. Is this a problem? Firebug doesn't show any of my ajax calls as completed, even thought the data is returned and the callback is executed. The recursive structure seems inefficient. Any ideas?

window.addEvent('domready', function()
{
    server =  new Request({
    url: "chat.php",
        method: 'get',
        link:   'ignore',
        onSuccess: callback,
    });

    request = server.send();
}

function callback(data)
{
    console.log(data);
    var data = JSON.decode(data);
    messId = data.max;
    for(var i = 0; i < data.messages.length; i++)
    {
        print("", data.messages[i].text);
    }
    var sendString = "messId="+messId;
    request = server.send(sendString);
}
A: 

You're right, you have to maintain a stack and closures for no purpose when you do long polling that way and depending on the situation and the implementation you might get a stack overflow or at least run low on memory... though I don't know for sure what optimizations the various js implementations perform (e.g. tail recursion which would make those problems go away).

The easy alternative is to use window.setTimeout(funcName) which will immediately call the function funcName when the current scope resolves, from the global scope.

Plynx
so I replaced:request = server.send(sendString);with:window.setTimeout("recieve()");and the functions still don't complete.
Teddy
Wait, since it's an asynchronous request, the callback function should finish, right?
Teddy
Yes, they should finish. Unless the requests are timing out... instead of finishing? You could at least try changing your last line to this `window.setTimeout(function(){server.send(sendString)});` Though I don't think the calls are recursive, browser HTTP requests are asynchronous like you said.
Daniel Beardsley
@Teddy Using a string as your setTimeout argument causes it to be evaluated which can mess with your scope and performance. Instead put an actual function expression in there, like a function literal or an anonymous function as Daniel put it in his comment. Second, test whether your callback is being called and completed by turning on tracing or putting in some log comments (or even an alert) to verify it (it should). If you aren't seeing it in Firebug's Net panel, try using Chrome or Safari's debuggers--Firebug itself has some wonky bugs.
Plynx