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?