首页 > 解决方案 > 下次调用该函数时退出 Java Script 中的循环

问题描述

我正在创建仪表板(图表)。这将每 3 秒更新一次。以下是我的代码的示例 html 按钮,

 <input type = "button" name = "cpuLoad" value = "CPU Load" onclick="getData('CPU')"/>
  <br></br>
  <input type = "button" name = "HeapMemory" value = "Heap Memory" onclick="getData('HEAP_MEMORY')"/>
  <br></br>

单击 cpuLoad 时,我需要来自数据库的 cpu 指标,以及用于堆内存指标的堆内存。这是我在 java 脚本中的 getData 函数,

async function getData(per) { 
  var type = document.form1.types.value;
  var state = 'live';
  if(state == "live"){
      setInterval(async function(){
           let data =  await fetch(`http://localhost:3001/api?type=${per}&state=${state}`);
           json = await data.json(); 
           await formatting(json, per, type);
        }, 3000);     
}

实际上,当单击一个按钮时,它会正常工作。它将每 3 秒更新一次。但是当我单击下一步按钮时,第一个请求的循环不会停止。两个请求都将运行(两个循环同时运行)。我交替地在我的 html 中看到这两个图表。这是错误的。当我单击下一个按钮或下一个请求时,我想退出上一个运行循环。我只需要输出当前请求。我怎样才能做到这一点?

标签: javascripthtmlnode.jsloops

解决方案


您可以使用 clearInterval 停止现有的 setInterval。我认为以下代码应该适合您。

var runningInterval = null;
async function getData(per) { 
  var type = document.form1.types.value;
  if(runningInterval != null)
      clearInterval(runningInterval);
  runningInterval = setInterval(async function(){
           let data =  await fetch(`http://localhost:3001/api?type=${per}&state=${state}`);
           json = await data.json(); 
           await formatting(json, per, type);
        }, 3000);      
}

推荐阅读