Reputation: 25914
I have a link that increases a value in the database provided it is below some threshold, something like this:
if (currentValue + 10 < maxValue)
{
$http({method: 'GET', url: 'api.increaseValue/10'}) ...
}
However if I click rapidly the if condition passes for all the clicks and launches a bunch of request concurrently that can take the value over the threshold. Is there a way to handle this elegantly?
Upvotes: 0
Views: 1004
Reputation: 364707
There are a number of ways to handle this issue. Besides what @praneetloke already mentioned, here are a few more ideas.
Upvotes: 3
Reputation: 1971
Use setTimeout() to delay the execution of the function. Also, use a global flag in the function that will return the function execution if that function is currently being executed for a previous click. Then, when your API call returns, reset the flag to allow subsequent clicks to call the function.
This suggestion also depends on what the value being incremented represents. You must decide if your users will be ok with ignoring fast-clicks. If they are intentionally doing it and you do not want to allow it, perhaps you must show a friendly message saying that a previous request is being processed and that they would have to wait before clicking again.
I could possibly improve the answer if you provide some context of this action and show more code of what else this function is doing.
Upvotes: 0