Example of Race Condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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