首页 > 解决方案 > 如何清除我的时间间隔并停止重复的 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);
            }
});

标签: node.jsexpressexpress-router

解决方案


间隔 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;
  }
});

推荐阅读