Search code examples
javascriptjquerylong-polling

Long Polling causes Maximum call stack size exceeded


I have this (attempt of) long polling function

I want to call this function in a certain time and then make the long polling work as long as the gallery has the updating class, gallery in this case is a $("... ")

function pollGallery(gallery){
    if (gallery.hasClass("updating")){
        var url = gallery.data("base") + "/refresh";
        $.ajax({ url: url, dataType: "script", complete: pollGallery(gallery), timeout: 30000 });
    }   
}

When I run this I get Maximum call stack size exceeded and from the logs it seems as if it doesn't either call the ajax or the timeout doesn't work..


Solution

  • Your code is not passing a callback function to complete, it simply calls a function recursively infinitely.

        $.ajax({ url: url, dataType: "script", complete: function() {
            pollGallery(gallery);
        }, timeout: 30000 });
    

    complete expects a function to be passed. By complete: pollGallery(gallery) you immediately call pollGallery(gallery) and attempt to assign its return value to the complete option, thus getting stuck in an infinite recursion loop.