Search code examples
javascriptangularjsrootscope

Unexpected behavior for $interval in .run block


I have an Angular JS application and I want to do a global action every second when the route changes successfully. So I created a .run() block in which I DI $interval and use the $interval on $routeChangeSuccess. The strange thing is that after each route change, the interval starts fireing faster and faster. This is my code:

app.run(["$interval", "$rootScope", function($interval, $rootScope){

$rootScope.$on("$routeChangeSuccess", function(event, current){
    if(current.$$route.authenticate){
        $interval(function(){
            console.log("whatever");
        }, 1000);
    }

});

}]);

To conclude, the "whatever" console log starts firing faster and faster. Is it because the $interval is a Singleton so it gets recreated each time? But why isn't the old $interval deleted?


Solution

  • I don´t understand why you want attach a new interval that is running every second on every routeChange. If I understand it correctly, you want it to check every second obly when route needs authenticate ? If so, you need to cancel the interval if the route is not authenticate anymore.

    you need to delete your $interval if you dont want it to be fired anymore.

    var stopTime = $interval(DoJob, 1000);
    
    // delete when you dont need it anymore.
    $interval.cancel(stopTime);
    

    see documentation for $interval

    app.run(["$interval", "$rootScope", function($interval, $rootScope){
    var intervalPtr = null;
    $rootScope.$on("$routeChangeSuccess", function(event, current){
        //page needs authentication
        //and interval was not set yet.
        if(current.$$route.authenticate && intervalPtr === null){
            intervalPtr = $interval(function(){
                console.log("whatever");
            }, 1000);
        // page that does not need authentication
        // reset only of there is a interval running
        } else if (intervalPtr !== null) {
             $interval.cancel(intervalPtr);
             intervalPtr = null;
        }
    
    });
    
    }]);