【问题标题】:calling clearInterval() in setInterval not stopping the setinterval在 setInterval 中调用 clearInterval() 不会停止 setinterval
【发布时间】:2021-03-01 11:00:47
【问题描述】:

我每 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);

【问题讨论】:

  • $('#txtMessage').text('Upload complete.'); 工作了吗?
  • 是否有任何其他代码 - 例如,您是否在循环中调用它?
  • 是的,它正在工作@freedomn-m
  • @@freedomn-m 我没有在循环中调用它
  • 一点一点分解。删除 ajax 调用,这样你就有了非常简单的方法,例如 jsfiddle.net/p6dmg0ea/1 然后添加 ajax 回调 - 在 setInterval 中添加一个 console.log(intervalId) 并且在 clearInterval 之前添加一个 - 它们是相同的值吗?您的 ajax 调用是否需要超过 5 秒?

标签: javascript jquery ajax


【解决方案1】:

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

  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多