Pregunta

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); 
}
¿Fue útil?

Solución

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();

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top