I have a web application where there is a timer that is constantly counting down. Meanwhile, the client frequently checks with the server to see if more time has been added to the timer. The code looks something like this:
function tick() {
// This function is called once every second
time -= 1;
redisplay(time);
};
function update(newtime) {
// This function is called whenever the ajax request
// to the server yields a new time
time = newtime;
};
It is, of course, a bit more complex than that, but you can see the inherent race condition. What if the update and the tick function are both trying to modify time
at the same time?
Frankly, I don't know nearly enough javascript to understand how to deal with this sort of concurrency issue: is there an easy way to do this, or if not, can somebody point me towards resources where I can learn more?
Thank you.
You don't have a race condition, because Javascript doesn't execute concurrently.
Every time a callback is fired from an async operation (AJAX, setTimeout
, etc), that callback must finish executing before another callback from another async operation can be called. So if update()
is running, no other Javascript is. Once update()
finishes, other callbacks from async operations can be fired (for example, tick()
). Interestingly enough, this is also why setTimeout
and its ilk aren't guaranteed to execute at the precise moment the timeout is reached: some other javascript could be blocking the callback's execution.
Check out http://ejohn.org/blog/how-javascript-timers-work/ for some good information on how all this works.
Javascript is single threaded. There is no race condition. There's no way in javascript for the two lines time = newtime;
and time -= 1;
to overlap during execution. In fact, the two functions are guaranteed not to overlap. One of them will run and then the other will run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With