Reputation: 1300
I need a help. i was trying to keep track of user clicks. The scenario is, i have list on which user can perform a click, on click a call to server has been made to fetch data. But i get stuck in situation, if user simultaneously click on list, multiple request reached to server.
What i want is only click call will happen and request to server for data.
Here what i've done till now.
function getData(id) {
_this.lastClickId = _this.currentId;
dataFactory.getListOfData(id).then(function(response) {
if(_.isEqual(_this.lastClickId , id)){
appendData(response);
} else {
getData(executionId);
}
});
_this.currentId = id;
}
here is my html code:
<ul>
<li ng-click="getData(1)">option1</li>
<li ng-click="getData(2)">option2</li>
</ul>
Upvotes: 0
Views: 42
Reputation: 48968
One technique is to use the ng-disabled directive to disable the submit button while the request is in progress.
<button ng-click="getData(id)" ng-disabled="inProgress">
Submit
</button>
$scope.getData = getData;
function getData(id) {
$scope.inProgress = true;
dataFactory.getListOfData(id)
.then(function(response) {
console.log("Success");
}).catch(function(response) }
console.log("error");
throw response;
}).finally(function() {
$scope.inProgress = false;
});
}
By disabling the Submit button, multiple clicks will be ignored while the request is in progress.
For elements other than inputs, the disabled state can be shown with the ng-style directive and by ignoring clicks when disabled:
<div ng-click="handleClick(id)" ng-style="inProgress?{opacity:'0.4'}:''">
Get {{id}}
</div>
$scope.handleClick = handleClick;
function handleClick(id) {
if ($scope.inProgress) return;
$scope.inProgress = true;
dataFactory.getListOfData(id)
.then(function(response) {
console.log("Success");
}).catch(function(response) }
console.log("error");
throw response;
}).finally(function() {
$scope.inProgress = false;
});
}
Multiple clicks will be ignored while the request is in progress and the element will be grayed out.
Upvotes: 1
Reputation: 1508
Maybe this solution will work for you.
You will need to figure out how many clicks you want to allow per second. Let's just say two for know.
var clickLimit = 2;
You will also need to keep track of the amount of clicks.
var clickCount = 0;
You are going to have to add 1 to the clickCount
everytime the user clicks.
Now you can set an interval every second which will remove a click from the clickCount
.
var clickInterval = setInterval(function () {
if (clickCount != 0) { clickCount -= 1; }
}, 1000);
Then put your code inside of a if
statement which checks the clickCount
against the clickLimit
.
if (clickCount <= clickLimit)
{
// action
}
Another, and possibily better way to do this, is by using a boolean which would allow the user to click or not. And an interval which would set the boolean to true
every second or whatever.
Upvotes: 1