× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Race conditions are evil

Sameer Maira
Nov 11, 2015
<p>Often times while writing code and testing it, one encounters a funny phenomena called the Race Condition.</p> <p>It's one of the more frustrating things to get around because it lives in the more Grey area of code.</p> <p>Not as simple and clear as 0 and 1. So what is it ?</p> <p>Lets look at an example:</p> <p>You have a function that modifies an image once it gets loaded on the page. But your function works sometimes and doesn't sometimes. More than often it works when you introduce a delay in execution, eg. Add a breakpoint, add an alert box , add a timer etc. This is super perplexing.</p> <p>What's going on here is that most probably your function runs before the image completely loads. When you introduce a delay it gives the image a chance to completely load before you move ahead and your function has all it needs, to execute as expected.</p> <p>So how do you solve it?</p> <p>Well you make sure you fulfill dependencies and execute in sequence. Make sure your method ALWAYS has what it expects. And if you think it won't, do appropriate error checking. If you're writing asynchronous code, make use of callbacks to chain execution.</p> <p>That's it!</p> <p>Hope this helps.</p> <p> </p>
comments powered by Disqus