1

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); 
}
7
  • Did you verify you're actually running one of the code blocks which calls clearInterval? Nov 16, 2011 at 21:41
  • Definitely do 2., window. shouldn't be written there explicitly, also for clearInterval. Style matters, too. :-)
    – user1046334
    Nov 16, 2011 at 21:44
  • Okay I found out that it works, but it just dont stop pooling instantly.. a couple of extra pools are done before it stops.. but why is that? Shouldnt it stop as soon as clearInterval is called? or is it some thread issue.. my application is multithreaded so maybe what I am seeing is just calls made from returning threads?
    – user750508
    Nov 16, 2011 at 22:04
  • It's polling, not pooling. Pooling means to create a pool Nov 16, 2011 at 22:06
  • What is this supposed to to? Send multiple requests until one of them comes back? How does this make any sense? Why are you sending multiple requests? Nov 16, 2011 at 22:07

2 Answers 2

0

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.