AngularJS interval example

One useful technique to keep content synced between client and server is doing continuous polling. Of course websockets are even better, but for this post, I’m going to just talk about the polling technique using AngularJS. AngularJS has an $interval service that can do this well. However, they do warn that you have to handle manually killing the interval service when you don’t want it to persist anymore like when you destroy a controller. This can be done with the following example code snippet.

var startedInterval;
$scope.startPing = function(num) {
    if (angular.isDefined(startedInterval)) {
        return;
    }

    startedInterval = $interval(function() {
        console.log("Ping " + num);
    }, 1000);
};

$scope.stopPing = function() {
    if (angular.isDefined(startedInterval)){
        $interval.cancel(startedInterval);
        startedInterval = undefined;
    }
};

$scope.$on('$destroy', function() {
    $scope.stopPing();
});

var num = Math.random();
$scope.startPing(num);

This is just a quick demonstration of this technique.

Leave a Reply

Your email address will not be published.