Question

I've got some very odd behaviour going on. I have the following JQuery:

myElement.fadeOut(100);

There is some kind of race condition going on, such that the element doesn't end up getting hidden. If I put a debugger on that line and step through the code, it works fine and the element fades out and gets hidden. Call it a Heisenbug.

My question is not about the race condition per se. I want to know how it is possible for this to happen given the nature of the JavaScript runtime. By my understanding the following predicates are true:

  1. fadeOut() is implemented by JQuery animate()
  2. animate() is implemented by a series of setTimeout() calls
  3. setTimeout() schedules the execution of a function in a queue at some point in time
  4. When events reach the start of the queue, the function is executed.
  5. There is only one event loop, which executes sequentially.
  6. At any given point in time, only one function / path through the callstack is executing.

Given that I am stepping through a function in my debugger, execution must be suspended and no other functions can be executing.

I cannot see how it is possible for a race condition to arise under these circumstances. Can you suggest how it is possible for execution to differ between debugged and non-debugged code?

Was it helpful?

Solution

Your bullet points are right, except that requestAnimationFrame() is used instead of setTimeout() if the browser supports it.

A debugging session can have an impact on the behavior of your code if, for instance, myElement is created asynchronously by an AJAX call but fadeOut() is called without waiting for the request to complete.

In that case, manually stepping through the code can give enough time for the request to return and the element to be created before fadeOut() is called, whereas the request would not have returned yet in the normal case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top