Reputation: 401
Doing some testing of a Jquery loop which calls a function within the loop 3 times. It seems like the function is called each time in the loop, but does NOT execute. At the end of the loop, the function then executes 3 times. Not what I want.
Why does the loadData not execute and append each time it is called? The alerts just tell me that each stage is performed as the loop cycles through.
My ultimate objective is to call a similar function each time until it fills the browser window to the bottom of the screen, then stop. But, with this behaviour, if I put a check in the loop for the condition of filled screen, it will not work since the screen will not fill at all as the loop churns.
Is there a way I can make this work, where a loop calls a function and the function actually executes each time it is called and do what it was designed to do?
Code below:
function loadData() {
alert('loadData function called');
$("#load_data").append("test");
}
var x = 0;
while (x < 3) {
x = x + 1;
alert('X number is: ' + x);
loadData();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="load_data"></p>
Upvotes: 1
Views: 115
Reputation: 370679
It looks like the rendering doesn't occur until the alert
stops blocking and the main thread completes. The test
is synchronously appended at the time the line runs in the Javascript, but the HTML the user can see doesn't visually change until the loop is finished.
One possibility would be for loadData
to return a Promise
that resolves immediately (right after there's been time for the rendering to take place), and for the loop to await
each call of loadData
, as in the snippet below. But it would be better not to use alert
at all - it's very user unfriendly, and blocking (like this) is almost never a good idea.
function loadData() {
alert('loadData function called');
$("#load_data").append("test");
console.log($("#load_data").text());
return new Promise(resolve => setTimeout(resolve));
}
var x = 0;
(async () => {
while (x < 3) {
x = x + 1;
alert('X number is: ' + x);
await loadData();
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="load_data"></p>
The same behavior occurs with the native textContent
:
const loadDataElm = document.querySelector('#load_data');
function loadData() {
alert('loadData function called');
loadDataElm.textContent += 'test';
console.log(loadDataElm.textContent);
}
var x = 0;
while (x < 3) {
x = x + 1;
alert('X number is: ' + x);
loadData();
// await loadData();
}
<p id="load_data"></p>
Upvotes: 3