I am dealing with a scenario where I have a function that alters some global state, and I need to figure out how to stop this function when a specific condition is met in order to avoid a race condition. Here's an example of the code to make it clearer.
let globalState = 0
const mutateState = () => {
setTimeout(()=> {
globalState = Math.random()
}, Math.random() * 1000);
}
<button onclick="mutateState()"></button>
Essentially, when the user clicks the button, I want to cancel any previous calls to the mutateState function so that the global state remains unchanged.
In addition, it's worth mentioning that I am using Vue.js (although not shown in this example).
Adding conditional statements before each globalState assignment isn't practical due to multiple variables being mutated in my actual code. It becomes cumbersome to add if statements for each one.
My ideal solution would be to completely abort the function.