Javascript: 从间隔函数中取消设置间隔?

Javascript: unset interval from within the interval's function?

我正在使用 setInterval 更新网站上一群人的用户统计信息。如果是 403,这意味着该组将此人踢出,我认为持续发送请求是不合理的,因为要返回该组,用户必须同意其个人资料页面上的某些内容。所以,假设我有:

setInterval(function() {
  $.ajax({
    method: 'GET',
    url: '/api/retreivestats',
    success: function(data) {
      //update the page with the new stats
    },
    error: function(errorObj) {
      if (errorObj.status == 403) {
        //someone took away the users perms to retrieve stats, unset the interval
      }
    }
  });
}, 30000);

如何使用错误函数中的实际取消设置此间隔?

您只需存储对区间的引用,然后使用 clearInterval

var myInterval = setInterval(function() {
  $.ajax({
    method: 'GET',
    url: '/api/retreivestats',
    success: function(data) {
      //update the page with the new stats
    },
    error: function(errorObj) {
      if (errorObj.status == 403) {
          clearInterval(myInterval);
      }
    }
  });
}, 30000);

设置一个变量并将setInterval赋值给它并使用clearInterval

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval

var interval = setInterval(function() {
   $.ajax({
     method: 'GET',
     url: '/api/retreivestats',
     success: function(data) {
       //update the page with the new stats
     },
     error: function(errorObj) {
       if (errorObj.status == 403) {
         //someone took away the users perms to retrieve stats, unset the interval
        clearInterval(interval);
       }
     }
   });
}, 30000);

interval is the identifier of the repeated action you want to cancel. This ID is returned from setInterval().