Based on my own experience, and consistent with this answer, changes to the UI aren't made while JavaScript code is running.
Example
When I click a button "Run Script", I want a loading animation to appear, then I want some JavaScript to run, and when the JavaScript is finished running, I want the loading animation to disappear. I've created a codepen here, which (predictably) fails. The most relevant portion of code is:
$('#run-script-btn').on('click', function() {
startLoading();
longLoadingScript(10000);
stopLoading();
});
startLoading()
changes the CSS to display a loader, but it doesn't actually affect the UI until the JS is finished running, at which point stopLoading()
is called - so essentially we never see the loading icon.
A workaround I came up with is to put a setTimeout()
around the longLoadingScript()
and stopLoading()
code in order to give the browser a moment to actually affect the UI in the startLoading()
call. The working code is in a codepen here, and the relevant portion looks like this:
$('#run-script-btn').on('click', function() {
startLoading();
setTimeout(function() {
longLoadingScript(10000);
stopLoading();
}, 100);
});
Question
Is that a good way to do it? Is there a better / more established pattern to handle this scenario?