11

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);
}
Reza
  • 880
  • 1
  • 10
  • 29
  • 1
    You can pass the return value of `$interval` to `$interval.cancel` to cancel the interval. You could also just have a branch inside the interval function that returns and does nothing if a boolean flag is set. – Alexis King Sep 08 '15 at 00:02

1 Answers1

10

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);
     }
     ...
Joy
  • 9,430
  • 11
  • 44
  • 95
  • 4
    Should be noted: this doesn't pause the interval and resume where it left off. It cancels the original interval and then starts it again from the beginning. – blitzmann Mar 29 '17 at 13:49