首页 > 解决方案 > 为什么这个 setInterval 函数没有立即清除

问题描述

请参阅以下代码。预期的行为将是在控制台中看到一个“100”,然后在清除间隔后仅此而已。然而,它实际上每次在清除之前记录 2-3 '100'。为什么没有立即清除间隔?

var endpoint = "https://example.com";
axios
  .post()
  .then(function(response) {
    var timerId = setInterval(function() {
      axios
        .get(endpoint + response.data.url)
        .then(function(response) {
          console.log(response.data.percentageComplete);
          if (response.data.percentageComplete == 100) clearInterval(timerId);
        })
        .catch(function(error) {});
    }, 1000);
  })
  .catch(function(error) {});

标签: javascriptaxios

解决方案


因为一旦 HTTP 请求成功完成,您就会清除它,而该请求可能需要几秒钟才能完成。同时,这些请求中的一个或两个以上由 触发setInterval


推荐阅读