繁体   English   中英

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

[英]calling clearInterval() in setInterval not stopping the setinterval

我每 5 秒发送一个带有 javascript setInterval 的 ajax GET 请求。 当收到的响应状态为“已完成”时,我想停止 ajax GET 调用。 因为我称 if 条件内的清除间隔。 但它并没有停止 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);

使用 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);
    }
  });

  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM