javascript function stops browser’s tab Code Answer

I have a problem with processing a Javascript function in the code below a simple example when I click the button in that code a Javascript function starts to process that function must change the value of the progress bar while it’s processing and the text area is shows when you try to type in that the page stopped and after a few seconds the browser gives a message

I intend to ensure that the function shows the value of the progress bar and I would like to do some tasks while the function is loading

       function f() {
            var i;
            for (i = 0; i < 100000; i++) {
                document.getElementById("p").innerHTML += i;
                document.getElementById("r").value += 1;
            }
        }
<html>

<body>
    <progress max="100000" value="0" id="r"></progress>
    <button onclick="f()">click here</button>
    <textarea placeholder="type here ..."></textarea>
    <p id="p"></p>

</body>

</html>

Answer

The problem is that Javascript is single-threaded. The browser is fully focusing on the calculations and does not have time to redraw. To remedy this, we need to provide some time to the browser to regroup:

       function f() {
            var i = 0;
            var intervalID = setInterval(function() {
                document.getElementById("p").innerHTML += i;
                document.getElementById("r").value += 1;
                if (++i === 100000) clearInterval(intervalID);
            }, 50);
        }
<html>

<body>
    <progress max="100000" value="0" id="r"></progress>
    <button onclick="f()">click here</button>
    <textarea placeholder="type here ..."></textarea>
    <p id="p"></p>

</body>

</html>

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji