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
foo
when a mobile page is loaded.At the end of
foo
, we usesetTimeout
to invokefoo
again (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_tap
and 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_tap
to start executing afterfoo
finishes? In other words, are we guaranteed that oncefoo
starts, we can never see execution offoo
anddo_tap
interleaved?What if the tap occurs first?
do_tap
is guaranteed to complete beforefoo
starts, right?