【问题标题】:AngularJs Update $interval delay time when this startedAngularJs 更新 $interval 延迟时间
【发布时间】:2015-01-28 05:22:27
【问题描述】:

我的html代码是:

<select ng-model='refresh_rate' ng-change="onRefreshRateChange()">
    <option value='10000'>10</option>
    <option value='30000' selected>30</option>  
    <option value='60000'>60</option>
    <option value='180000'>180</option>
    <option value='300000'>300</option>
</select>

在我的角度控制器中是:

var intervaL = $interval(function(){
    //[here]
    //after run every times i want update delay to $scope.refresh_rate
}, $scope.refresh_rate);

在上面的代码中看到这一行: //这里我想更新延迟时间到$scope.refresh_rate

现在我想要一个代码来代替这一行

【问题讨论】:

  • 那里有太多与问题无关的代码。发布问题时,尝试将代码减少到仍然重现并突出显示您的问题的最少代码。这将帮助其他人帮助你。
  • @new-dev 对不起我的不好问...我想在每次运行 $interval 到 $scope.refresh_rate 的更新延迟后使用 angularjs $interval 函数
  • 您始终可以(并且应该)编辑您的问题以清理它。这就是这些 cmets 的重点
  • @NewDev 完成...我编辑了我的问题.. 我该怎么做?
  • 最简单的方法是创建一个 $timeout 循环,然后您可以每次都将新的 $timeout 设置为 $scope.refresh。

标签: angularjs


【解决方案1】:

要更改$interval 速率,您需要停止一个$interval 并启动另一个。

无需详细说明最后一次 $interval 呼叫是否应该立即触发或取消 - 我会让你自己处理 - 你可以执行以下操作:

var p = $interval(doSomething, $scope.refresh_rate);

$scope.$watch("refresh", function(){
  $interval.cancel(p);
  p = $interval(doSomething, $scope.refresh_rate);
});

function doSomething(){
  //...
}

plunker

编辑

您当然也可以在 onRefreshRateChange 而不是 $scope.$watch 中执行此操作。不同之处在于您是否愿意在&lt;select&gt; 之外更改$scope.refresh_rate - 这是您将使用$watch 与仅响应&lt;select&gt; 更改的地方

【讨论】:

  • doSomething 功能大部分在控制器功能中?
  • 它需要被控制器函数访问,但是是的 - 最好放在控制器函数中。
  • 这个问题是它会在触发它之前取消间隔函数,所以你可能会在这里和那里错过调用。
  • @ZackArgyle,是的,这就是为什么我说“不谈细节”和“我会让你自己处理”,因为这在原始问题中没有被指定为要求。
  • 什么?! :) 这是一个问答网站 - 在这里问你需要什么,我或其他人都会帮助你
【解决方案2】:

使用 $timeout 循环。

function loop(fn) {
    $timeout(function() {
        if (!$scope.stopBefore) {
            fn();
            $scope.stopAfter || loop(fn);
        }
    , $scope.refresh);
}
loop(doSomething);

【讨论】:

  • 这是一个好方法 - 只要不需要立即取消并启动另一个计时器。
  • 添加了一些可用于控制的标志。
  • 但是不能马上启动下一个定时器。我更重要的一点是 - OP 的要求不准确
  • @ZackArgyle 我最常使用 $scope.refresh 而不是 $scope.refresh_rate ??
  • @ZackArgyle 工作,但如果从 New Dev Answer 中找到我的答案.. 无论如何都会让你失望:X
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-05
  • 2018-01-24
  • 2010-11-08
  • 1970-01-01
  • 2015-03-08
相关资源
最近更新 更多