I’m just reading a bit into JavaScript and came over some code that handle the process of loading images:
var n = 0;
...
for (...) {
...
image[i].onload = function { n++; };
}
Is this piece of code safe or can there be any type of race while accessing the variable n?
The time at which the ONLOAD event for each image is raised (relatively to each other, if at ever) is generally non-deterministic. Consider issues like browser cache or concurrent downloads, or failed attempts.
However, there is only one JavaScript “execution context” at a time; that is, the final value of
nwill reflect the total amount of times that ONLOAD handler is invoked (at that given time). That is, for a given page, all JS is atomic until it finishes (yields to the browser until an event occurs)“Web Workers” also fit within this event model; there is no traditional “race condition” between threads and variable access. However, any shared (mutable) state between tasks can result in a race-condition, albeit at at higher-levels.