Dan
Dan

Reputation: 93

Electron.JS is being very CPU intensive, I can't tell what's wrong with my code

I have written an application to show GPU/CPU/RAM loads in electron.js! It was all ok until I started implementing gauges to graphically display temperatures. This section is shown below, I have also included a screenshot of task manager showing hundreds of command and powershell windows!

 function getGPUtempHome(){
     let stinker = si.graphics();
     stinker.then(function(tempGPU){
         GPUtempHome = tempGPU.controllers[0].temperatureGpu;
         console.log(GPUtempHome);
         document.getElementById("GPUtemps").innerHTML = GPUtempHome+'°';
         document.documentElement.style.setProperty('--GPUTEMP', GPUtempHome*1.8 + 'deg');
     });
     setInterval( function() {getGPUtempHome();}, 5000 );
 }

 function getRAMhome(){
     let stinker3 = si.mem();
     stinker3.then(function(RAM){
         RAMUSAGE = Math.round(((RAM.used/RAM.total)*100));
         console.log(RAMUSAGE);
         document.getElementById("RAMloads").innerHTML = RAMUSAGE+'%';
         document.documentElement.style.setProperty('--RAMLOAD', RAMUSAGE*1.8 + 'deg');
     });
     setInterval( function() {getRAMhome();}, 5000 );
 }

The code above fetches RAM load or GPU temperature every 5 seconds, it then updates a HTML/CSS gauge.

If writing a program like this is unviable in electron.js are there any other better options out there, I am open to playing around with new languages/libraries.

Upvotes: 1

Views: 1624

Answers (1)

tadman
tadman

Reputation: 211590

Remember, setInterval() sets a recurring timer, so your code is basically saying "Every five seconds create another timer for every five seconds." After ten seconds you will have 2 timers. After 20 you now have 8. After 60 seconds you have 4,096 of them. Every 5 seconds the number of timers doubles.

That sounds like a problem, doesn't it?

What you want to do is set one timer, once, per function:

function getRAMhome(){
    let stinker3 = si.mem();
    stinker3.then(function(RAM){

        RAMUSAGE = Math.round(((RAM.used/RAM.total)*100));
        console.log(RAMUSAGE);
        document.getElementById("RAMloads").innerHTML = RAMUSAGE+'%';
        document.documentElement.style.setProperty('--RAMLOAD', RAMUSAGE*1.8 + 'deg');
    });
}

// Set timer outside of the function
setInterval(getRAMhome, 5000);

It's a common problem to confuse setInterval() which sets a repeating timer with setTimeout() which sets a one-shot timer that needs to be re-engaged. You're treating the former like the latter, with disastrous consequences.

Upvotes: 3

Related Questions