0
\$\begingroup\$

I found there are two methods to code an if-else statement with a timeout function. Two of these scripts work fine, but which one of them is more preferable and why?

Method One

app.controller("filter", function($scope, $timeout) {
    $scope.expand = function() {
        $timeout(function() {
            if ($scope.expandCollapse === "expand-up")
                $scope.expandCollapse = "expand-down";
            else
                $scope.expandCollapse = "expand-up";
        }, 1500); 
    };
});

Method Two

app.controller("filter", function($scope, $timeout) {
    $scope.expand = function() {
        if ($scope.expandCollapse === "expand-up")
            $timeout(function() {
                $scope.expandCollapse = "expand-down";
            }, 1500);
        else
            $timeout(function() {
                $scope.expandCollapse = "expand-up";
            }, 1500);
    };
});
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I am not familiar with angular, but if $scope.expand can be called multiple times in a short time these two snippets will behave differently. The question is: What behaviour do you want? \$\endgroup\$ Commented Feb 28, 2016 at 16:23

1 Answer 1

1
\$\begingroup\$

Both pieces of code do different things. The first one schedules first, evaluates state second while the second one does the opposite, evaluating the state first, and schedule the timer second.

If this is part of animation code, where those strings are class names and the delay is intended to delay the animation, I suggest you move over this delay to CSS transitions instead. That way, it will all be just manipulating the value of expandCollapse without the timing element.

$scope.expand = function() {
  var isExpandUp = $scope.expandCollapse === "expand-up";
  $scope.expandCollapse = isExpandUp ? "expand-down" : "expand-up"; 
};
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for replying. What you mean is remove the $timeout from Angular and add the time delay in CSS right? \$\endgroup\$ Commented Mar 1, 2016 at 1:53

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.