1

I created a plugin to display a busy indicator in DOM elements like body or divs, but im having a problem with the situation bellow

$("body").BusyIndicator(true,"Please wait")

validateAndSubmitForm(); 

$("body").BusyIndicator(true,"Saving") 

The problem is the first message "Please wait" isn't shown, the function validateAndSubmitForm seems to block the browser, and when it is unlocked, show directly the message "Saving"

Someone knows how can i ensure that the first message really are displayed before to execute the function validateAndSubmitForm ?

Lucas Konrath
  • 567
  • 2
  • 8
  • 19

1 Answers1

4

The browser has a single thread to interpret the javascript and update the interface. It can't do both simultaneously. You have to let some time to the browser so it can update the interface:

$("body").BusyIndicator(true,"Please wait");

setTimeout(function() {
    validateAndSubmitForm(); 

    $("body").BusyIndicator(true,"Saving");
}, 0);

setTimeout with a timer of 0 tells the browser to execute the function as soon as possible after it was able to update the interface (and do some other stuff like processing user input, ...)

Volune
  • 4,324
  • 22
  • 23
  • thanks,i tryed to use setTimeout inside of the validateAndSubmitForm passing the same validateAndSubmitForm(indicated for an example that i found) as parameter , but some strange behavior happened, like many submits in the form. I use your example and work fine,but after save one time, the first message isn't shown again.. but i alter the timeout to 100 and seems to work, so, i can have any problem with this? – Lucas Konrath Aug 13 '14 at 13:19
  • 1
    Here are some explanations about the queuing of javascript execution and UI updates : [Why is setTimeout(fn, 0) sometimes useful?](http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful) and video [High Performance JavaScript](https://www.youtube.com/watch?v=_fUGWFGUrUw) at 17:40 – Volune Aug 13 '14 at 13:56