Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pause a angular interval and then resume

I have a function that i repeat every 10 second. This works fine. It shows orders. Now i want a accept order function. But when this is clicked i want to pauze the interval. And when accept order returns i want to resume this interval again.

what is the best way to do this?

my code

    if ($auth.isAuthenticated()) {
    //request
    $scope.checkNewOrders = function (){
        newOrderService.getNewOrders().then(function (response) {
            //console.log(response.data.status);
            if (response.data == 'token_error') {
                $auth.logout();
            }

            if (response.data.status == 'success') {
                $rootScope.openOrders = response.data.data;
            }

            if (response.data.status == 'no_orders') {
                $rootScope.openOrders = false;
            }
        });
    };

    //Put in interval, first trigger after 10 seconds
    $interval(function(){
        $scope.checkNewOrders();
    }.bind(this), 10000);

    //invoke initialy
    $scope.checkNewOrders();
}

$scope.acceptOrder = function(orderid) {
    console.log(orderid);
}
like image 614
Reza Avatar asked Sep 08 '15 00:09

Reza


1 Answers

You should create a variable of the $interval:

var timer = null;
$scope.checkNewOrders = function (){ ...

timer = $interval(function(){
    $scope.checkNewOrders();
}.bind(this), 10000);

Then inside the click function, cancel the timer:

$scope.acceptOrder = function(orderid) {
    $interval.cancel(timer);
    timer = null;
}

After the update finishes, resume:

newOrderService.getNewOrders().then(function (response) {
     if (timer === null) {
         timer = $interval(function(){
             $scope.checkNewOrders();
         }.bind(this), 10000);
     }
     ...
like image 93
Joy Avatar answered Oct 20 '22 15:10

Joy