Skip to content

Instantly share code, notes, and snippets.

@craigmr
Last active August 29, 2015 14:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save craigmr/5e83e12fb2e102c7b43f to your computer and use it in GitHub Desktop.
Example of Race Condition
/**
* calculateZ() is a simplified version of a race conidtion. We have two ansync tasks
* that modifiy the state before each call is complete.
*/
function calculateZ() {
let x = 0, y = 0, z;
//Async call to get the true value of y
setTimeout(() => y = 2, Math.random() * 1000);
//Async call to calculate z using value of x and y.
setTimeout(() => {
x = 2;
z = x + y;
console.log(z);
}, Math.random() * 1000);
}
//Lets run it a 100 times. This will simulate refreshing the browser.
for (let i = 0; i < 100; i++) {
calculateZ();
}
//If you run calculateZ function 100 times you will get either an output of 2 or 4?
//What's going on?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment