I have a long running Javascript function, that looks like this:
window.myFunction = function() {
for(var i=0;i<500;i++){
// calling a function here
document.getElementbyID('mySpan').innerHTML = "Completed step " + i + "/500"
}
}
My function calls another synchronous function very often (I used 500 in this example) and while the user waits for the task to complete, i'd like to implement something like a loading bar but I demonstrated it with updating a span in my case here. Is it possible to force a DOM refresh of some sort every time I update my span?
Use DOMContentLoaded event callback You can use the DOMContentLoaded event as the trigger for executing your code. Do this by using document. addEventListener() to tie a custom function to the event. This example shows you how to define a custom function that will execute only after the DOM is loaded.
log() yields this result isn't surprising because a DOM update is a synchronous event.
Invoking a JavaScript FunctionThe code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function". It is also common to say "call upon a function", "start a function", or "execute a function".
Since scripts run in a single thread in your browser, any method like yours will need to complete before the DOM is updated. What you can do, however, is use an iterative function with a small delay that allows the browser to redraw.
Here's an example...
window.myFunction = function(i) {
// calling a function here - passing i as a parameter, if needed
document.getElementById('mySpan').innerHTML = "Completed step " + i + "/500";
i++;
if (i <= 500) setTimeout(function() { myFunction(i) }, 1);
}
myFunction(0);
<span id="mySpan"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With