$ interval发生了太多次

时间:2015-04-28 21:00:49

标签: javascript jquery angularjs

希望我能解释一下,这样你才能理解。我刚刚完成了一个问题,获得了有关angular $interval功能的帮助。让我们先从基础开始:

  • 我有一个用户选择选项的下拉列表。
  • 该操作调用select方法生成$http.get( ) 请求。
  • 然后使用mg-repeat将结果数据放入列表中。
  • 可以从其他服务更新数据,因此我需要此列表 定期轮询并刷新列表,输入$interval

在下面的代码中,我很接近,但并不完全存在。假设我想每10秒刷新一次列表,如果我从开始选择选项1,它将每10秒刷新选项1的列表。好的吗?

现在,如果我选择选项2,就我所理解的而言,似乎它会创建另一个线程。它将$http.get( )从选项1更改为选项2,但它会保持选项1的$interval线程打开。所以它在10秒内两次选项2 $http.get( )。一旦跟随第一个请求的时间间隔(对于选项1),并且在我选择选项2的时间间隔内一次。

这是select函数的JS代码。当用户从下拉列表中选择某些内容时会发生这种情况:

    $scope.select = function() {
      $scope.searchText = '';
      $scope.selectedItem = null;
      var url = 'http:xxxxxxxxxxxx.com';
      url += $scope.selectModel.name;
      console.debug("GOING TO: " + url);
      $http.get(url).success(function(data2) {
        $scope.records = [];
        data2.forEach(function(r) {
            $scope.records.push(r);
        });
      });
      $interval(function() {
        $http.get(url).success(function(data2) {
        $scope.records = [];
        data2.forEach(function(r) {
            $scope.records.push(r);
        });
      });
    }, 30000);
};

以下是问题html的部分:

<div style="margin: 1em">
<h4>Search</h4>
        <div role="form">
            <!-- start dropdown -->
            <div class="form-group">
                <select class="form-control" ng-options="model as model.name for model in allModels" ng-model="selectModel" ng-change="select()">
                    <option value="">Choose Model</option>
                </select>
            </div>
            <!-- /end dropdown-->
            <div class="form-group">
                <input id="start_date" type="text" class="form-control" placeholder="Threat Date">
            </div>
        </div>
    <div>
        <table class="table table-hover table-striped" ng-show="records">
            <thead>
                <th>#</th>
                <th>Name</th>
                <th>Score</th>
            </thead>
            <tr data-ng-repeat=" item in records | orderBy : '-score' | limitTo : 10 " ng-click="moreInfo(item)">
                <td>{{$index+1}}</td>
                <td>{{item.name.slice(5)}}</td>
                <td>{{item.score.toFixed(3)}}</td>
            </tr>
        </table>
    </div>
</div>

如果我需要澄清一些,请告诉我。感谢。

1 个答案:

答案 0 :(得分:3)

您需要取消间隔。

// Activate
var myInterval = $interval(....);

// Deactivate
$interval.cancel(myInterval);
myInterval = undefined; // Necessary for conditional checking
相关问题