Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

jquery - Race conditions with JavaScript event handling?

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:

  1. We invoke function foo when a mobile page is loaded.

  2. At the end of foo, we use setTimeout to invoke foo again (with one second delay) if a counter is greater than 0. If the counter hits 0, we load a new page. The timeout is saved in a variable.

  3. 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:

  1. Assume a tap occurs during the execution of foo. Will the browser queue do_tap to start executing after foo finishes? In other words, are we guaranteed that once foo starts, we can never see execution of foo and do_tap interleaved?

  2. What if the tap occurs first? do_tap is guaranteed to complete before foo starts, right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...