Search code examples
javascriptdom-events

Click events being lost?


I have a web page (JavaScript) that has two types of events:

  • Click event in a canvas (only displays an alert).
  • Periodic event (fired by a timer) every second.

The periodic event is busy for 200 - 300 ms (it's launching a synchronous SOAP call).

The canvas event:

var c=document.getElementById("myCanvas");
 c.addEventListener('click', function(e) {alert('Click');},false);

The periodic:

var timer1= new Timer(1000,"Refresh()"); // A library call


function Refresh()
{   
    timer1.stop();

    // Synchronous SOAP call would come here

    // with the results we draw the canvas again

    timer1.start();
}

If I click in the canvas while the SOAP call is being made, the click event is not being fired, or so I assume, because the alert is not shown.

If I click once the periodic event is finished and before it gets called again, every click shows the alert.

From what I know, if the click event is generated while the periodic event is being executed, it should be delayed until the other one is finished.

What could be causing the problem?

P.D. I'm using Firebug (on Firefox) to know when the SOAP call is being made.


Solution

  • Synchronous calls block the I/O, so the alerts would not be fired. Since you are waiting for a return for your call, any actions that happen during that time will be ignored.

    This article may prove to be helpful: http://ejohn.org/blog/how-javascript-timers-work/

    Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution.

    • JavaScript engines only have a single thread, forcing asynchronous events to queue waiting for execution.
    • setTimeout and setInterval are fundamentally different in how they execute asynchronous code.
    • If atimer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
    • Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).