Reputation: 5520
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
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.
Upvotes: 1
Views: 305
Reputation: 5955
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!
Upvotes: 1
Reputation: 563
I think this is to be expected. You're calling
$('#cal').append(html)10,001 times. Each time you do this you're modifying the DOM which is an expensive operation.
If you really need to write out 10001 div class='row' elements you might be better off writing them all to a string then doing one append. It's still not ideal but it's hard to see a better solution without knowing more about what you're trying to achieve.
function loadCalendar() {
var i=0;
var html = '';
while (i <= 10000) {
html += '<div class="row"></div>';
i++;
}
$('#cal').append(html);
}
Upvotes: 0