0

I have seen many posts regarding aborting AJAX requests using .abort() function such as this post, but it just doesn't work for me.

I make repeated AJAX calls after every 30 seconds using setTimout, and there is a point where I would like to stop the repeating calls from occurring based on a condition.

Am I doing something wrong or is it that .abort() has been deprecated? I'm using jquery version 1.9.1.

Community
  • 1
  • 1
Rahul Dole
  • 2,723
  • 2
  • 24
  • 30
  • Are you using a setTimeout function to call them? – Brett Weber Jul 11 '13 at 14:18
  • Yes, and i use that in the complete function – Rahul Dole Jul 11 '13 at 14:20
  • 1
    Have you tried using a setInterval instead, storing the id, clearInterval at the point when you do not want to call it again? [This may help as well..?](http://stackoverflow.com/a/446626/1257652) Without more context and some code to see what is going on, I'm not sure how else to help. :/ – Brett Weber Jul 11 '13 at 14:24
  • 1
    Oh yes! It's working perfectly now! Amazing to see that using just setInterval instead of setTimeout made all the difference.. thanks a lot :) – Rahul Dole Jul 11 '13 at 14:57
  • Let me write up a solution for you since this solved the problem so you can mark an answer, I'll edit your question a bit and set this up to help someone else in the future. – Brett Weber Jul 11 '13 at 15:05
  • There we go, all fixed up I think! Maybe you could add a simplified example of your code as well? – Brett Weber Jul 11 '13 at 15:24
  • 1
    Thanks for posting your solution as an answer, I was about to suggest that. The first code block in your answer almost matches my code. Should I edit my question to include the code anyway? – Rahul Dole Jul 12 '13 at 05:11
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33320/discussion-between-rahul-dole-and-brett-weber) – Rahul Dole Jul 12 '13 at 05:18

1 Answers1

1

Instead of using:

var xhr = null;
ajaxOfTheSort = function
(
   xhr = $.ajax
   (
      success : function()
      {
         /* Do something */ 
         setTimeout( ajaxOfTheSort, 30000 );
      }
   );
)

if (/* condition */)
   xhr.abort();

try using setInterval() :

var oInterval = setInterval
(
    function()
    {
       if (/* condition */)
          clearInterval( oInterval );
       else
          $.ajax
          (
             success : function() { /* Do something */ }
          );
    },
    300000
)
Brett Weber
  • 1,839
  • 18
  • 22