计数事件然后使用 throttle/debounce 执行事件
Count event then using throttle/debounce to execute event
如何在 angular 中使用下划线 throttle/debounce 来计算事件触发的 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 毫秒调用一个 "heavy duty" 函数,所以您是这样做的:
<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++;
});
}
你应该快速点击按钮,你会看到油门观察器不会在你每次点击按钮时更新,但最多每 500 毫秒更新一次。
如何在 angular 中使用下划线 throttle/debounce 来计算事件触发的 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 毫秒调用一个 "heavy duty" 函数,所以您是这样做的:
<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++;
});
}
你应该快速点击按钮,你会看到油门观察器不会在你每次点击按钮时更新,但最多每 500 毫秒更新一次。