How to tell javascript to update the DOM immediately?

I am trying to load a β€œload” message to a user before a time function is called in javascript.

HTML:

<p id='foo'>Foo</p>​ 

JavaScript:

 var foo = document.getElementById('foo'); function tellViewerLoading() { // Tell the user that loading is occuring. foo.innerHTML = 'loading...'; } function someActionThatTakesALongTime() { // Do some action that takes a long time. var i = 0; while(i < 100000) {i++; console.log(i);}; } function domUpdateDelayExperiment() { tellViewerLoading(); someActionThatTakesALongTime(); } domUpdateDelayExperiment(); 

JSFiddle: http://jsfiddle.net/johnhoffman/xDRVF/

I want the DOM to be updated immediately after the call to tellViewerLoading() .

Instead, what happens is that the DOM seems to be updated after someActionThatTakesALongTime() . At this point, it is useless to display a boot message.

How to tell javascript to update the DOM immediately after calling tellViewerLoading() ?

+4
source share
2 answers

Create a long run function using setTimeout:

 function domUpdateDelayExperiment() { tellViewerLoading(); setTimeout(someActionThatTakesALongTime, 50); } 

Explanation: The tellViewerLoading() function updates the DOM, but the browser will not display the changes on the screen until domUpdateDelayExperiment() returns. someActionThatTakesALongTime with setTimeout (), we allow the browser to reflect DOM changes. The timeout is arbitrary, but its minimum value may be important in some browsers. The value of 50 ms is fairly fair.

+4
source

Actually, if you execute your code using the debugger, you will see that the download text will be changed before the next function is called.

Your browser simply hangs on a long function call, so it cannot change the displayed text.

Using a short timeout can help if you want your browser to have enough time to change the display before moving on to the next function.

+1
source

All Articles