node.js - 如何清除我的时间间隔并停止重复的 API 调用?
问题描述
我有一个表单,点击开始后,我开始了一系列 API 调用,这些调用间隔为 15 秒。当我单击停止时,我想停止 API 调用并清除间隔。出于某种原因,尽管我点击了停止并且我的代码说它确实进入了清除间隔的代码部分,但调用仍然继续进行。
app.post("/", (req,res) => {
if(req.body.hasOwnProperty("start")) {
var t = setInterval(function() {
axios.post(url, data,config)
.then(res => {
// do stuff
})
.then(res => {
// do stuff
})
.then(res => {
// about three thens after this
})
}, 30000)
} else {
console.log("Clearing Interval")
clearInterval(t);
}
});
解决方案
间隔 id 应该存储在一个全局变量中,可以从不同客户端的请求中访问。
而且我想,您只想为间隔运行一个动作。-> 在创建新的之前应该检查现有的 intervalID
所以它应该是这样的:
let intervalID;
app.post("/", (req,res) => {
if(req.body.hasOwnProperty("start")) {
if (!intervalID) {
intervalID = setInterval(function() {
axios.post(url, data,config)
.then(res => {
// do stuff
})
.then(res => {
// do stuff
})
.then(res => {
// about three thens after this
})
}, 30000)
}
} else {
console.log("Clearing Interval")
clearInterval(intervalID);
intervalID = null;
}
});
推荐阅读
- python - Python 每月删除异常值
- html - 更改折叠面板内容背景颜色
- html - XSLT 转换输出仅显示第一页并且图形被截断
- c++ - 如果程序运行超过一定时间限制,则命令终止/停止程序
- google-bigquery - BigQuery 中自(可能不存在)日期以来的前向填充
- api - 文本框中不显示文本
- php - 拒绝,因为 php8.0 可能会导致无效的组合
- notifications - 当构建在依赖项后面排队时,Teamcity 通知?
- firebase - “用户”不是函数。尝试更正名称以匹配现有函数,或定义名为 'User'.dartinvocation_of_non_func 的方法或函数
- javascript - 使用 XHR 请求 API 时出现 CORS 错误