cieux123
cieux123

Reputation: 19

Intentional delaying in Angularjs

I am making a little diagnose web page and want to make it look like the system is working hard in background by showing loading image for a while.

I am not a programmer. so I basically look all over for a chunk of codes that works and this is how I tried... but justDelaying function never delays the later process. It seems all the process is running simultaneously.

app.controller('HardworkCtrl', function($scope, $timeout) {

    $scope.hardWork = function() {

        // start showing hard-working image
        $scope.loading = true;

        $scope.justDelaying = function() {
            $timeout(function() {
                // do nothing...
            }, 5000);
        }
        $scope.justDelaying();

        $scope.theAnswer = "42."

        // stop showing hard-working image
        $scope.loading = false;

    };
};

Any idea?

Upvotes: 0

Views: 43

Answers (1)

Kevin
Kevin

Reputation: 6014

Anything that happens inside "$timeout" is asynchronous, so it's just scheduled for later, without blocking the main execution. In other words, the instructions after you call $scope.justDelaying() happen immediately, while the instructions inside justDelaying get delayed for 5 seconds. To make those instructions execute later, you need to move them inside the $timeout, like this:

app.controller('HardworkCtrl', function($scope, $timeout) {

    $scope.hardWork = function() {

        // start showing hard-working image
        $scope.loading = true;

        $scope.delayThenDoStuff = function() {
            $timeout(function() {
                $scope.theAnswer = "42."

                // stop showing hard-working image
                $scope.loading = false;
            }, 5000);
        }
        $scope.delayThenDoStuff();
    };
};

Upvotes: 2

Related Questions