在javascript中停止时间间隔

Ram*_*ran 9 javascript setinterval angularjs

目前我正在使用角度js

我有一个get方法从default.html页面的服务器端获取数据

function bindActiveLoans() {
            $http.get(rootUrlSingleEscaped + '/cooperativa/allunfundedloans/?authId=' + userInfo.UserId)
                 .success(function (response) {
                     if (response.Loans.length == 0) {
                         $scope.IsValues = false;
                         $scope.$apply();
                         return true;
                     }
                     $scope.IsValues = true;
                     $scope.unfundedLoans = response;
                 });
        };

        setInterval(function () {
            $scope.$apply(bindActiveLoans());
        }, 5000);
Run Code Online (Sandbox Code Playgroud)

上述功能有助于每5秒调用服务器端方法.这对我来说非常有用.

但我有一个问题.我有更多的页面,页面是

  • default2.html,default3.html,default4.html,default5.html.

    如果我运行我的default.html页面,计时器每5秒运行一次,那么我将转到另一页,此时该计时器正在运行.我想只显示默认页面上运行的计时器.如果我转到另一页,那么计时器应该停止???

你知道吗?

当我转到另一个页面(default2.html,default3.html,default4.html,default5.html)页面时,如何在默认页面中停止计时器?

我想在默认页面中使用clearInterval

nac*_*bre 16

来自$ interval API页面中的angularjs示例.

    var interval = $interval(function() {
        console.log('say hello');
    }, 1000);

    $interval.cancel(interval);
Run Code Online (Sandbox Code Playgroud)

使用$ interval.cancel(var)你可以停止间隔,如果你想在导航到另一个页面时停止它,你应该尝试这样的事情.

var interval = null;

module.controller('SomeController', '$interval', function($interval) {
    interval = $interval(function() {
        ...
    }, 2000);
}).run(['$rootScope', '$interval', function($rootScope, $interval) {
    $rootScope.$on('$routeChangeStart', function() {
        $interval.cancel(interval);
    });
}]);
Run Code Online (Sandbox Code Playgroud)