javascript - 为什么这个 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) {});
解决方案
因为一旦 HTTP 请求成功完成,您就会清除它,而该请求可能需要几秒钟才能完成。同时,这些请求中的一个或两个以上由 触发setInterval
。
推荐阅读
- php - PHPSpreadsheet 无法在 Excel 中获取注释
- java - Jetty 11 - HTTP/1.1 到 HTTP/2 升级,handler 怎么写?
- javascript - 在 TypeScript 中的另一个类型别名中传播类型别名
- weka - 在 Weka 中打开 CSV 数据集时,如何将属性转换为“日期”类型?
- python - 如何在networkx中找到几何子图的最近邻?
- c# - 不能在同一帧缝合网格
- tkinter - 如何使 tkinter 小部件全局化
- c++ - 获取用户输入时,它会显示最后的输入
- android - 如何从 Firestore 数据库中读取单个特定字段值并在 android 的片段 TextView 中设置
- .net - 通过.net Core在cosmos mongodb中创建和调用存储过程