Search code examples
javascriptfreezevisual-studio-cordova

Cordova freeze UI during long Javascript while


I can't create a working example, but the code is simple.


Configuration

IDE: Visual studio 2017

Target platform: Windows x64

System: Win 10

My project: Javascript // Blank App (Apache Cordova) // ver. 6.3.1


HTML // index.html

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <header></header>
        <main>
            <div id="cal">

            </div>
        </main>
        <footer>
            <!-- ## this creates a simple pure css loader ## -->
            <div class="progress">
                <div class="indeterminate"></div>
            </div>
            <a href="#" class=".addItem">Add</a>
        </footer>

        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="scripts/platformOverrides.js"></script>

        <script src="frameworks/jquery-3.2.1.min.js"></script>
        <script src="frameworks/materialize/js/materialize.min.js"></script>        

        <script type="text/javascript" src="scripts/index.js"></script>

    </body>
</html>

Javascript // index.js

(function () {
    "use strict";


    document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );

    function onDeviceReady() {

        $(document).ready(function () {
            $('.addItem').on('click', function () {
                setTimeout(function () {
                    loadCalendar();
                }, 5000);
            });

        });

    };


    function loadCalendar() {
        var i=0;
        while (i <= 10000) {
            var html = '<div class="row"></div>';
            $('#cal').append(html);
            i++;
        }
    }


} )();

App starts and the UI work as expected, the progress loader show his css animation. After clicked the button addItem all work for 5 seconds and then the UI freez until the while loop end. I don't think it is normal, how can I solve it ?

Thanks

Edit

An important clarification

I don't expect the DOM to be updated during the loop, and this code above is not the real code, it is only usefull for understanding and test. The real loop is much shorter and faster, but it is still a problem.

What happens is that the whole interface freezes, the whole app. The CSS animation should be totally independent from Javascript, but is freezes!

Here an example of what I expected

I hope this clarify the point better.


Solution

  • As stated in the comment, all loop declarations are blockers, and before the loop has finished - even the most trivial hover effect will not be able to respond.

    JavaScript is linear, synchronous and a single-threaded process. To circumvent the freeze condition, you will need to move your loop operation on to a separate thread.

    E.g.: On another - separate instance, of a document!