1

In my application, I add a loaderDiv to avoid all userevents on the page.

The loader appears. If the user force a clickevent(eg. greenContainer onclick) the event is fired after the loader div disappears.

I've created a short example the show you the problem

js:

function appendOverlay(){
    var maskDiv = $('<div id="overlay" class="loadmask" onclick:"return false;"><div class="removeDiv" onclick="sleep(3000)"><span>click to remove overlay after 3 seconds</span></div></div>');
        $('body').append(maskDiv);
    }

    function removeDiv(){
        $("#overlay").remove();
    }

    function sleep(milliseconds) {
      var start = new Date().getTime();
      for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
          break;
        }
      }
      removeDiv();
    }

Demo

How can I solve this problem?


Solved this problem by using setTimeout(removeDiv(),0). This is a problem with the event loop execution in Javascript.

Propergate the removeDiv() to the next tick and the userEvent onClick() is execute first.

Why is setTimeout(fn, 0) sometimes useful?

The JavaScript Event Loop

Community
  • 1
  • 1
SancezZ
  • 43
  • 4

1 Answers1

1

Strange 'sleep' function there. Why don't u use the internal timeout :

function sleep(milliseconds) {
    setTimeout(function() {
         removeDiv();   
    }, milliseconds);
}

DEMO

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • I can't do it in async way. In this example I wait 3 second. In my application i modify data. This can take a long time (eg 3 seconds). In this time window the user must be stoped to force userevents. – SancezZ Jul 25 '14 at 09:40
  • U can't modify data if u hang the browser for 3 seconds with that sleep function of yours. Using this method the user can't on anything so there are no userevents? – DarkBee Jul 25 '14 at 09:50