javascriptelectron

How to force UI draw in ElectronJS prior to intense computation task?


I am building an Electron program to identify molecular ions from precise mass determinations. The calculation can take several seconds or even a few minutes. To let the user know that it is processing, I would like to change the text on the button that starts the calculation to "Processing..." before the intense calculation begins. But Everything I try results in the change being displayed after the calculation completes!

In principle I thought this would work, as a similar code works for reading the atomic mass database before parsing it.

function fnFindSCM(){

  async function showProcessing() {
    document.getElementById("btnFindSCM").innerHTML = "Processing...";   
  }

  async function awaitShowProcessing(){
    await showProcessing();

  }

  awaitShowProcessing();

  reallyFindSCM();

}

The function fnFindSCM() is the button's click event listener, while reallyFindSCM() is the function that does the heavy calculations.

I am hoping that a solution to this problem will also solve my next problem -- displaying "hits" as they are found rather than all at once when the search is complete.


Solution

  • Your async function showProcessing() needs to return a Promise in order for the timing to work as you would expect. Here's how I would restructure the code you provided:

    function fnFindSCM() {
        async function showProcessing() {
            return new Promise(resolve => {
                document.getElementById("btnFindSCM").innerHTML = "Processing...";
                resolve();
            });
        }
    
        showProcessing()
            .then(() => {
                // Allow UI to update before calling the next function
                return new Promise(resolve => setTimeout(resolve, 0));
            })
            .then(() => reallyFindSCM())
            .catch(error => console.log(error));
    }