Race conditions are the bogeyman of concurrent programming. When they happen, they are hard to spot and even harder to reproduce.
Races can happen any time you have concurrent processes operating on the same data – especially without going through an explicit synchronization mechanism.
Having worked with threads, coroutines, semaphores, mutexes, locks and other abstractions across a handful of different programming languages, I’ve caused my fair share of race conditions. So typically, I’m extra vigilant when working with concurrent code.
In this particular case I was building a cancellable delete animation.
To cause the race you have to start deleting a second element before the first has completed. This could be very easily overlooked and it is easier to spot if we slow the animation down.
The array index of the element you intended to remove will change any time an item before it is removed. If the index changes during the animation the wrong element is removed.
The solution in this case was to add a unique identifier rather than an index to control the removal of elements.
Front end code is asynchronous due to callbacks and events. Front end component state is shared memory. These two features together are a recipe for race conditions, so keep an eye out, and be careful out there.
If you’d like to see a live example of this code, you can find it here:
Loved the article? Hated it? Didn’t even read it?
We’d love to hear from you.
Interesting. Here’s an alternative solution that doesn’t require SetTimeout: https://codepen.io/ben-wexler/pen/LYxJRee
(I understand your example was to illustrate a situation with callbacks, but I was just curious if it was possible to solve this a different way).
What do you think?
Leave a comment