I'm running up against a roadblock in Javascript that I can't seem to overcome.
Is there any way of “updating” a view while a loop of API calls is running?
For example:
for (var x =0; x<array.length; x++) {
//do an api call
console.log(“Processing “+x+” of “+array.length+” records.”);
};
The above outputs the value of x for each loop to the console. However, this:
for (var x =0; x<array.length; x++) {
var body = document.getElementById(“view_100”);
//do an api call
body.innerHTML = “Processing “+x+” of “+array.length+” records.”;
};
Does not update the dom until after all of the loops have finished and then shows only the last value of x.
Any thoughts on how I can keep a user informed as to what is going on during a long javascript loop?
var array = [1,2,3,4,5] for (var x = 0; x<array.length; x++) { var body = document.getElementById("view_100"); //do an api call //append the text instead of reassigning body.innerHTML += "Processing "+(x+1)+" of "+array.length+" records."; /* cleaner way var message = document.createElement("p"); message.innerText = "Processing "+(x+1)+" of "+array.length+" records." body.append(message) */ };
<div id="view_100"></div>
you can use append element
const body = document.getElementById(“view_100”);
for (var x =0; x<array.length; x++) {
const statusEl = document.createElement('div');
statusEl.innerHTML = `Processing ${x + 1} of ${array.length} records`
//do an api call
body.appendChild(statusEl);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.