How JavaScript Avoids Race Conditions

Posted Wed Dec 26 @ 09:57:24 AM PDT 2012

One thing I've never understood was how JavaScript can avoid race conditions when running code asynchronously (like in an event, AJAX, setTimeout() or setInterval() callback). Yes, JavaScript is single threaded, but that doesn't guarantee a race condition free environment.

Here's a simple example:

We have a function that will change the state of the flag variable after 30 milliseconds. And we busy wait until that happens. Can the assertion fail? That would occur if JavaScript executes the condition in the while loop, and drops down to the assert. But at that moment, the setTimeout() timer expires, and JavaScript switches contexts and starts executing the callback. The callback changes the flag to false. When it finishes, JavaScript resumes where it left off at the assert...and the assert fails.

Can that possibly happen in JavaScript? No. JavaScript will actually patiently wait for the main thread of execution to go into a wait state before executing any asynchronous callback. So in the above case, the setTimeout() callback will never execute, because the thread is always busy.

<< Home