Question

I have a problem with the code below. Basically im implementing a polling mechanism, but when it is supposed to stop polling it just continues to poll. Polling infinite.

Is there any other way to force it to stop?

The function SearchPoll is only called once.

function SearchPoll(){
    var i = setInterval(function () 
    { 
        var url = "Search.aspx?polling=true";        
        $.ajax( 
        { 
            url: url,
            success: function (data) 
            {     
                clearInterval(i); 
            }, 
            error: function () 
            { 
                clearInterval(i); 
            } 
        }); 
    }, 1000); 
}
Was it helpful?

Solution

If you want to kill all requests you need to work with the XMLHTTPRequest object returned from $.ajax. Here is an example:

function SearchPool(){
    var xhrArray = [], 
        interval = setInterval(function () { 
            var url = "Search.aspx?polling=true";        
            xhrArray.push($.ajax({ 
                url: url,
                success: function (data) {     
                    for(var i = 0; i < xhrArray.length; i+= 1) {
                        xhrArray[i].abort();
                    }
                    clearInterval(interval); 
                }, 
                error: function () { 
                    clearInterval(interval);
                } 
            })); 
        }, 20);
}
SearchPool();

OTHER TIPS

This fiddle seems to work correctly... http://jsfiddle.net/sramam/yZTAK/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top