We understand that JavaScript is single threaded, but we want to confirm our understanding of asynchronous event handling in JavaScript. More importantly, we want to confirm we’re not exposed to potential race conditions.
Conceptually, our mobile app works like this:
-
We invoke function
foowhen a mobile page is loaded. -
At the end of
foo, we usesetTimeoutto invokefooagain (with one second delay) if a counter is greater than0. If the counter hits0, we load a new page. The timeout is saved in a variable. -
If a button is tapped, we invoke function
do_tapand clear the timeout variable saved in step two (and do other stuff).
do_tap and foo both update the same page element, and we want to confirm that they wouldn’t step on each other.
Questions:
-
Assume a tap occurs during the execution of
foo. Will the browser queuedo_tapto start executing afterfoofinishes? In other words, are we guaranteed that oncefoostarts, we can never see execution offooanddo_tapinterleaved? -
What if the tap occurs first?
do_tapis guaranteed to complete beforefoostarts, right?
Except for web workers and cooperating frames or windows (which aren’t being used here), Javascript is single threaded within a given window so there are never two threads of execution running at the same time in that window. As such, you don’t ever have to worry about race conditions that might be a typical worry when using threads.
Under the covers, Javascript has an event queue. Your current thread of execution will run to completion and then when it completes, the javascript interpreter will check the event queue to see if there are more things to do. If so, it fires that event and starts up another thread of execution. Pretty much everything goes through that event queue (timers, key events, resize events, mouse events, etc…).
You can read more about it and see a bunch of relevant references in one of my other answers on this subject.