Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating DOM during Javascript function execution

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?

like image 445
Daniel Gretzke Avatar asked Sep 25 '17 11:09

Daniel Gretzke


People also ask

How do I run a DOM in JavaScript?

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.

Are DOM events synchronous?

log() yields this result isn't surprising because a DOM update is a synchronous event.

What is invoke function?

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".


1 Answers

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>
like image 155
Reinstate Monica Cellio Avatar answered Sep 27 '22 22:09

Reinstate Monica Cellio