javascript - 计数事件然后使用throttle/debounce来执行事件

标签 javascript angularjs underscore.js

如何在 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

   */
}

https://jsfiddle.net/6w747zzL/

最佳答案

正如我在评论中所写,您使用 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 毫秒最多更新一次。

工作示例:https://jsfiddle.net/6w747zzL/2/

关于javascript - 计数事件然后使用throttle/debounce来执行事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43046315/

相关文章:

javascript - 如何在 ng-repeat 上获取两个 Controller 的结果

javascript - 如何 ng-if 另一个 div 可见

javascript - HTML 5 延迟属性

javascript - 下划线 _.each 和 _.map 之间的真正区别是什么?

带名称的 Javascript 动态函数调用

javascript - 从主干 View 中的模板获取 DOM 元素

javascript - 如何在主干 View 中加载外部 html 模板

javascript - 设置 cookie 并在第一次访问时显示 div 然后隐藏

javascript - 为什么在我的 AngularJS + RequireJS 应用程序中 Controller 被创建了 2 次?

javascript - 检查两个对象之间的键是否匹配的最简单方法是什么?