Search code examples
javascriptphpajaxxmlhttprequest

i would like to stop ajax request after 2 minutes


My ajax function works every 15 seconds. I would like to stop it after 2 minutes.

How can i do this?

 window.setInterval(function () {
      var request = $.ajax({
         ...
      })
 }, 15000);

Solution

  • Use clearInterval, the clearInterval() method clears a timer set with the setInterval() method.

    var request;
    var _timer = setInterval(function() {
    
      request = $.ajax({
        ...
      });
    
    }, 15 * 1000);
    
    setTimeout(function() {
    
        clearInterval(_timer);
        request.abort(); // If you want to abort the xhr which are still executing after 2 minutes
    
    }, 2 * 60 * 1000);