如何在 Angular 中使用下划线 throttle /去抖来计算事件触发的 x 次。然后在一定的时间间隔后,在知道 x 的情况下触发事件?
html
<div ng-app ng-controller="testC">
<input type="submit" ng-click="add()" value="add"></input>
{{counter}}
</div>
js
function testC($scope) {
$scope.counter = 0;
$scope.add = function () {
$scope.counter++;
}
/*
counter x-timed add has triggered
after interval has been reached trigger a event that does $scope.counter = $scope.counter + x
*/
}
最佳答案
正如我在评论中所写,您使用 throttle 每 X 毫秒调用一次“重载”函数,因此您可以这样做:
<div ng-app ng-controller="testC">
<input type="submit" ng-click="add()" value="add">
counter: {{counter}} <br>
throttle: {{ throttle }}<br>
non-throttle: {{ nonthrottle }}
</div>
function testC($scope, $timeout) {
$scope.counter = 0;
$scope.add = function () {
$scope.counter++;
}
$scope.throttle = 0;
$scope.$watch('counter', _.throttle(function(value) {
// Wrapping this in '$timeout' will ensure a digest cycle execute that will update the view (Since underscore is not native angular function)
$timeout(function() {
$scope.throttle++;
});
}, 500));
$scope.nonthrottle = 0;
$scope.$watch('counter', function(value) {
$scope.nonthrottle++;
});
}
您应该快速单击该按钮,您会发现 throttle 观察器不会在每次单击该按钮时更新,而是每 500 毫秒最多更新一次。
关于javascript - 计数事件然后使用throttle/debounce来执行事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43046315/