javascriptjqueryvariableslong-pollingself-executing-function

Setting a variable in a recursive JQuery/Javascript self-executing function (polling)


I need to set a variable (tick) with an initial value in a recursive self-executing JQuery script. When I try and run the script below obviously tick is going to revert back to 0 rather than the value the JSON object is returned with.

    (function poll(){
        var tick = 0;
        setTimeout(function(){
            $.ajax({
                url: "/client-polling/" + tick,
                success: function(data) {
                    $( "#messagestack" ).append(data[2]);
                    tick = data[0]
                },
                dataType: "json",
                complete: poll
            });
        }, 10000);
    })();

Also for some reason when I have tick declared the function waits the entire 10 seconds before polling the first time. If I try to declare tick outside of the function all other scripts on the page freeze up.

Where do I declare tick so the first time the page is called it's set to 0 and then takes the value from the returned JSON object?

Update: Well it took most of the Eloquent Javascript book and 7 Douglas Crockford videos to figure out what the problem was and I had failed to realise that Javascript is single-threaded. I've read through so much of other peoples coding it had not really occurred to me that usually their scripts run through once and go on to the next. My 'event-loop' was stopping other scripts from running, and yes, on its own the function should have the variable on the outside.

I finally ended up using iFrames (non-public, single interface application so security not a concern) just to get it running and now looking at web workers for future builds. Thanks for the answers so far.


Solution

  • Why don't just set a variable outside the function?

    var tick = 0;
    (function poll(){
        setTimeout(function(){
            $.ajax({
                url: "/client-polling/" + tick,
                success: function(data) {
                    $( "#messagestack" ).append(data[2]);
                    tick = data[0]
                },
                dataType: "json",
                complete: poll
            });
        }, 10000);
    })();