javascript - 下次调用该函数时退出 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 中看到这两个图表。这是错误的。当我单击下一个按钮或下一个请求时,我想退出上一个运行循环。我只需要输出当前请求。我怎样才能做到这一点?
解决方案
您可以使用 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);
}
推荐阅读
- java - @RequestMapping 注解中路径和值属性的区别
- java - 休眠搜索不起作用
- c# - C# 7.3 枚举约束:为什么我不能使用可为空的枚举?
- azure - 在 azure 中发布项目后无法将响应重定向到我的控制器:AuthBot
- apache-poi - Is disposing SXSSFWorkbook necessary when used in try with resource
- python - 在循环中删除特定的字典值
- sql-server-2014 - SQL 数据库图 - SQL Server 2014?
- amazon-web-services - 在 Cognito 内置登录页面中显示用户名以外的其他内容
- javascript - 为什么 XMLHTTP 请求不适用于我的服务器?
- django - 如何使用 Django 将自定义对象传递给表单