间隔并停止重复的API调用?"/>
我如何清除间隔并停止重复的API调用?
我有一个表单,在其中单击开始时,我开始一系列的API调用,这些调用的间隔为15秒。单击停止时,我想停止API调用并清除间隔。由于某些原因,尽管我按下了stop并且我的代码说它确实进入了我的代码中清除间隔的那一部分,但调用仍然继续发出。
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;
}
});
更多推荐
我如何清除间隔并停止重复的API调用?
发布评论