John Hoffman
John Hoffman

Reputation: 18667

How do I tell javascript to immediately update the DOM?

I am trying to load a 'loading' message to the user before a time-intensive 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/

What I want to happen is for the DOM to be updated immediately after tellViewerLoading() is called.

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

How do I tell javascript to immediately update the DOM after tellViewerLoading() is called?

Upvotes: 14

Views: 25252

Answers (2)

Claudi
Claudi

Reputation: 5416

Spawn the long-time running function with setTimeout:

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

Explanation: the tellViewerLoading() function updates the DOM but the browser won't reflect changes on screen until domUpdateDelayExperiment() returns. By delaying someActionThatTakesALongTime by means of setTimeout() we let the browser to reflect DOM changes. The timeout is arbitrary, but its minimum value may be important in some browsers. A value of 50 ms is fair enough.

Upvotes: 11

Florian Margaine
Florian Margaine

Reputation: 60835

Actually, if you step through your code using a debugger, you will see that the loading text is changed before the next function is called.

Your browser is just hanging at the long function call, so it can't change the displayed text.

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

Upvotes: 2

Related Questions