Reputation: 514
I'm having a problem with jQuery waiting for additional javascript to execute before updating the DOM. In the example code below, the h1 element isn't updated for >5 seconds after the SlowUpdate function is called. I'm using chrome, but observed the same issue in IE. I know it's not strictly related to the console logging because my actual project is not logging text to the console. Rather, the issue seems to be related to the time it takes the rest of the function to execute.
Any links to detailed explanations of this behavior or potential solutions would be greatly appreciated!
HTML:
<!DOCTYPE html>
<html>
<!--Load jQuery libraries-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<!--Load Javascript functions-->
<script src="Scratch.js" type="text/javascript" name="ScratchJS"></script>
<body>
<h1>Hello Change?</h1>
</body>
</html>
Javascript:
$(document).ready(function () {
$("h1").click(function () {
SlowUpdate();
});
});
function SlowUpdate() {
// This change isn't made before moving into the loop
$("h1").text("Change Complete");
// Take a bunch of time doing stuff
var i = 0;
while(i < 100000) {
console.log(i);
i++;
}
}
Upvotes: 0
Views: 579
Reputation: 55623
jQuery isn't waiting to update the DOM, the main thread (the UI thread, the same thread JavaScript is executed on) is blocked because it's busy running a loop.
Go ahead, run this in you console and you'll see it's not a jQuery specific issue:
(function() {
document.body.innerHTML = 'test';
var i = 0; while(i < 1000000000000) { i++; }
}());
Upvotes: 1
Reputation: 1497
For an explanation, I found this answer as well as other solutions for similar problems.
A potential solution:
$(document).ready(function () {
$('h1').on('mousedown', function() {
$("h1").text("Change Complete");
})
$("h1").on('mouseup', function () {
SlowUpdate();
});
});
function SlowUpdate() {
// Take a bunch of time doing stuff
var i = 0;
while(i < 100000) {
console.log(i);
i++;
}
}
Upvotes: 0