我如何清除间隔并停止重复的API调用?

编程入门 行业动态 更新时间:2024-10-06 20:29:17

我如何清除<a href=https://www.elefans.com/category/jswz/34/1769353.html style=间隔并停止重复的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调用?

本文发布于:2024-05-13 09:18:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!