在 setInterval 中调用 clearInterval() 不会停止 setinterval

时间:2021-03-01 11:00:47

标签: javascript jquery ajax

我每 5 秒发送一个带有 javascript setInterval 的 ajax GET 请求。当响应状态接收为“已完成”时,我想停止 ajax GET 调用。因为我在 if 条件下调用 clear 间隔。 但它并没有停止 setInterval。

var intervalId = window.setInterval(function() {

  console.log('Trigger!!');

  $.ajax({
    type: "GET",
    enctype: 'application/json',
    url: url,
    processData: false,
    contentType: false,
    crossDomain: true,
    cache: false,
    timeout: 600000,
    success: function(dataNew) {

      console.log('dataaa get' + JSON.stringify(dataNew));

      if (dataNew.jobStatus === 'COMPLETED') {
        $('#txtMessage').text('Upload complete.');

        clearInterval(intervalId);

      }

    },
    error: function(e) {
      $('#btnSubmit').prop("disabled", false);
      $('#txtMessage').text('Error Occured');

      clearInterval(intervalId);

    },
    beforeSend: function(xhr) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);

    },
    complete: function() {

    }
  });


}, 5000);

1 个答案:

答案 0 :(得分:0)

使用如下所示的ajax调用:

var interval = setInterval(callAjaxFunc, 5000); 
function callAjaxFunc() {
 console.log('Trigger!!');

  $.ajax({
    type: "GET",
    enctype: 'application/json',
    url: url,
    processData: false,
    contentType: false,
    crossDomain: true,
    cache: false,
    timeout: 600000,
    success: function(dataNew) {

      console.log('dataaa get' + JSON.stringify(dataNew));

      if (dataNew.jobStatus === 'COMPLETED') {
        $('#txtMessage').text('Upload complete.');

       clearInterval(interval);

      }

    },
    error: function(e) {
      $('#btnSubmit').prop("disabled", false);
      $('#txtMessage').text('Error Occured');

      clearInterval(interval);

    },
    beforeSend: function(xhr) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);

    },
    complete: function() {
        clearInterval(interval);
    }
  });

  
}