1

I have a simple html code below. The alert dialog is shown before the html and the innerHTML only shown after click OK on dialog.

Question is how to show the html element "sort_arr" before alert dialog

<!DOCTYPE html>
<html>
<body>

<h2>Sort</h2>

<p id="orig_arr"></p>
<p id="sort_arr"></p>
<button onClick="abcSort()"/>Sort Alphabet</button>
<button onClick="numSort()"/>Sort Numeric</button>

    <script>
        var arr = [1, 3, 11, 200, 8, 201, 1000, 50000];
        var new_arr = [2,1,1,5,7,100,3,2];
        document.getElementById("orig_arr").innerHTML = "Original array " + arr;
        
        function abcSort() {
            document.getElementById("sort_arr").innerHTML = "Abc sort : " + arr.sort();
        }
        
        function numSort() {    
            document.getElementById("sort_arr").innerHTML = "Abc sort : " + arr.sort(function(a,b) {return a-b});       
            alert(new_arr.sort(function(a,b) { return a - b} ));            
        }
    </script>
</body>
</html>
hoangnh
  • 249
  • 4
  • 13

1 Answers1

1

To achieve that, you need to run the alert message on the next event cycle. You could do that with setTimeout() with an empty delay. Like this

<!DOCTYPE html>
<html>
<body>

<h2>Sort</h2>

<p id="orig_arr"></p>
<p id="sort_arr"></p>
<button onClick="abcSort()"/>Sort Alphabet</button>
<button onClick="numSort()"/>Sort Numeric</button>

    <script>
        var arr = [1, 3, 11, 200, 8, 201, 1000, 50000];
        var new_arr = [2,1,1,5,7,100,3,2];
        document.getElementById("orig_arr").innerHTML = "Original array " + arr;
        
        function abcSort() {
            document.getElementById("sort_arr").innerHTML = "Abc sort : " + arr.sort();
        }
        
        function numSort() {    
            document.getElementById("sort_arr").innerHTML = "Abc sort : " + arr.sort(function(a,b) {return a-b});       
            setTimeout(() => alert(new_arr.sort(function(a,b) { return a - b} )));            
        }
    </script>
</body>
</html>
JayCodist
  • 2,424
  • 2
  • 12
  • 28