How to detect when the browser has finished updating the view (re-layout, apply any modified CSS)


I have code that I'd like to run that looks something like this pseudocode:

  1. Apply some CSS style to some element

  2. Do some other action

The issue is that I need to not do the 'other action' until after I'm certain that the browser has actually rendered the changed CSS and will be visible to the user.

Although javascript is single threaded, and if the 'other action' blocks the javascript from executing further, I'd think that the browser would hopefully still be able to update the view with the new CSS values set in step 1, even if javascript itself is blocked - but that doesn't appear to be happening (the CSS changes don't show up until after step 2 - in this case a remote service call - completes).

Adding to Grezzo's comment, you can use a JS timeout of 0 to ensure the previous line of code has finished executing. This works because it puts whatever is inside the setTimeout's closure at the very end of the internal queue of code to be run. E.g.

// Update CSS
$('#mydiv').css({'position' : 'relative', 'top' : 0});
setTimeout(function() {
}, 0);

I'm too n00b on StackOverflow to post a link, I think, otherwise you can read the "MASTERING THE REFRESH() METHOD" section here:

"Here we placed the refresh call into a zero timeout, doing so we gave the browser the time to refresh itself and the new element dimensions are correctly taken. There are other ways to ensure the browser actually updated the DOM, but so far the zero-timeout has proven to be the most solid."