the display and hiding of loader divs is not working synchronously as intended in javascript

Just found a solution, which is to wrap the Solver function with a setTimeout function to provide time for the DOM to update:

solveButton.onclick = function (){
      //Return error if input invalid
      if (textArea.value.length != 81) {
        return (document.getElementById("error-msg").innerHTML =
          "<span style='color: red'>Error: Expected puzzle to be 81 characters long.</span>");
      }

      //Show Loader
      document.getElementById("container").style.display = "none";
      document.getElementById("loader").style.display = "flex";
      
      /////////////SET TIMER//////////////
      setTimeout(function() {
        //Start timing
        const t0 = performance.now(); 
        
        //Run Solver
        let solution = solveSudoku()

        //Error Handling. Uncomment loader once loader issue fixed

        if (!solution) {
          //document.getElementById("loader").style.display = "none";
          //document.getElementById("container").style.display = "flex"
          return (document.getElementById("error-msg").innerHTML = "<span style='color: red'>Error: Invalid initial input.</span>");
        }
        if (solution == "no solution") {
          //document.getElementById("loader").style.display = "none";
          //document.getElementById("container").style.display = "flex"
          return (document.getElementById("error-msg").innerHTML = "<span style='color: red'>Error: No solution found.</span>");
        }
        console.log("Final boardState", solution);

        //Populate elements with solution
        let solutionString = "";
        for (let idx in solution) {
          solutionString += solution[idx].value;
        }
        textArea.value = solutionString;
        Array.from(sudokuInputs).forEach((ele, idx) => {
          ele.value = solutionString[idx];
        });

        //Hide Loader. Uncomment once loader issue fixed
        document.getElementById("loader").style.display = "none";
        document.getElementById("container").style.display = "flex";

        //Stop timing and show performance
        const t1 = performance.now();
        document.getElementById("error-msg").innerHTML = `<span style='color: lightgreen'>Solved in ${(t1-t0 > 50)?(t1 - t0).toFixed(3):"less than 50"} milliseconds!</span>`;
      }, 50)
      
      
      
    };

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top