0

I am creating dashboard (graphs). That will update for every 3 seconds. The following is the sample html buttos of my code,

 <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>

when click cpuLoad i need cpu metrics from data base, and Heap memory for Heap memory metrics. This my getData function in java script,

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

Actually when click one button it will work correctly. it will updated each 3 seconds. but when i click next button then the loop for the first request won't stop. both requests will be running(both loops running at a time). I see both graphs in my html alternatively. this is wrong. when i click next button or next request i want exit from the previous running loop. i need output of only the current request. how can i achieve this?

2 Answers 2

1

You can use clearInterval to stop your existing setInterval. I think the following code should work for you.

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);      
}
Sign up to request clarification or add additional context in comments.

Comments

1

to cancel an already repeating setInterval you can use clearInterval

read more about it here https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.