skip to Main Content

I’m trying to stop my setInterval() call. The best would be to identify whenever my AJAX request is fulfilled. So, If I got my AJAX GET response, then clearinterval().

$(document).on('submit', '#post-form', function(e) {
  e.preventDefault();

  $.ajax({
    type: 'POST',
    url: '/send',
    data: {
      room_name: $('#room_name').val(),
      csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
    },
    success: function(data) {
      //alert(data)
    }
  });

  $(document).ready(function com() {

    loop = setInterval(function() {
      $.ajax({
        type: 'GET',
        url: "/trafic",
        success: function check(response) {
          //SOME CODE//

        },
        error: function(response) {
          //SOME CODE//
        }
      });
    }, 1000)
    setTimeout(clearInterval(loop), 10000);

  })
});

I tried to set a timeout, but it is very imprecise as it may take longer/shorter than the delay. So I would need something like if GET successful {clear interval()}

2

Answers


  1. You need to move the clearInterval() call into the success callback of the AJAX call. You’ll also need to move the loop interval higher up in your code so that it can be referenced from the success callback.

    I’m also not sure why the loop interval is wrapped in a $(document).ready() call, because you can be assured that the document is ready if it is submitted. Also, the variable loop is awfully ambiguous. Try using the name of the API endpoint instead, like traffic.

    Try this code:

    $(document).on('submit', '#post-form', function(e) {
      e.preventDefault();
    
      const traffic = setInterval(function() {
        $.ajax({
          type: 'GET',
          url: "/trafic",
          success: function check(response) {
            clearInterval(traffic);
          },
          error: function(response) {
            //SOME CODE//
          }
        });
      }, 1000);
    
      $.ajax({
        type: 'POST',
        url: '/send',
        data: {
          room_name: $('#room_name').val(),
          csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        },
        success: function(data) {
          // some code
        }
      });
    });
    
    Login or Signup to reply.
  2. Can I ask you first why did you use setInterval on this HTTP request ? You are probably using more computation power than you need.

    You should probably make the request async (e.g https://petetasker.com/using-async-await-jquerys-ajax)

    If you want to wait for an event to appear, you may want to have a look at web sockets (https://www.tutorialspoint.com/websockets/index.htm)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search