Keith Fosberg Keith Fosberg - 4 years ago 165
Ajax Question

Javascript cursor: sequence of events

I have been searching but can't find anything relevant to my issue. I need to change the cursor when a user initiates an action so they don't shotgun the request.

The statement to change the cursor is simple enough, but I can't get it to fall into sequence correctly. My cursor doesn't change until the function completes. I can see this by commenting out the statement to return the cursor to normal behavior.

I want the cursor to go to wait and stay that way until the call tot he ajax function is done, then return to normal.

// wrapper to set wait cursor during ajax calls (the cursor change doesn't work, btw -- leaving it here so it can be fixed)
function loadForm(){
setTimeout("document.getElementsByTagName('BODY')[0].style.cursor = 'wait'",1);
setTimeout("document.getElementsByTagName('BODY')[0].style.cursor = 'auto'", 1);

// configure calls to populate entire page: first string identifies the call, the second string identifies the custom function to implement
function populateReadPage(){

Answer Source

Javascript execution is single-threaded, so this is what happens when you execute the loadForm function:

  1. setTimeout(Action1,1) : Action1 is enqueued to be executed when the current (main) execution line finishes
  2. populateReadPage() : This method is executed
  3. setTimeout(Action2,1) : Again, Action2 is enqueued to be executed when the current (main) execution line finishes.
  4. Nothing else in the main line, Action1 is executed
  5. Action2 is executed

UPDATE: After some research, it seems that the body style changes need a "pause" to be set, so I made it work with the following code:

function loadForm(){ = 'wait'; //sets the cursor to wait

  setTimeout(()=> { //enqueues the tasks
     populateReadPage(); = 'auto'; //once all is done, sets the regular pointer

Just one thing: the cursor does not change until it moves, not sure why

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download