0

I'm trying to build a task processing type of SPA. The idea is There are 10 steps, The user clicks submit, then a service will be called to begin a process, and the UI will wait. Once it gets a response a style will be applied for success for failure. Anyhow, right now I'm trying to mock this behavior up and I can't seem to get my Angular correct, specifically with $timeout. Below is my code, and please excuse the simplified example I'm trying to understand Angular by working through it.

;function(angular) {
 'use strict'

  angular.module("workApp", [] )
    .controller ("TaskController", function ($routeParams, workService, $timeout, $scope) {
   var tc = this;

   // These will be used in the view to flip the CSS to the appropriate color for success or failure
   tc.step_0_status = "ready";
   tc.step_1_status = "ready";
   tc.step_2_status = "ready";

   // trying this out, by storing my functions in a array, b/c I will have other uses in the end for this array.
   var func_array = [
      function(){step_0},
      function(){step_1},
      function(){step_2}
    ]

  // This is where I am misunderstanding $timeout I guess. I simply want the loop to sleep for 3 seconds, before the next function is called.
  $scope.startTasks = function results() {
    for(var x = 0; x < func_array.length; x++) {
       **$timeout(func_array[x](),3000);**
    }

   }

  var step_0 = function() {
    tc.step_0_status = "running"
   }

  var step_1 = function() {
    tc.step_0_status = "completed";
    tc.step_1_status = "running";
   }

  var step_2 = function() {
    tc.step_1_status = "completed";
    tc.step_2_status = "failed";
   }


}
})(window.angular);
1
  • In this case you need use $interval, not timeout. Commented Jun 15, 2016 at 21:37

1 Answer 1

2

You can use a $interval to create the sleep method you want:

$interval(function(){
    // do wahetever you need here
    console.log('running');
},3000, func_array.length);

just make sure to destroy it properly after you have used it

Sign up to request clarification or add additional context in comments.

4 Comments

nice, don't forget to mark it as an answer! I'm glad that wotked for you
Yep, and if I could freaking type to get my reply to show up as code.. :P Anyway, thanks. I'm really diggin Angular. I didn't know you could pass a object like that (func_array.length) to $interval. That's pretty sweet.
One more question, what is the proper way to destroy it?
look at the documentation, there's an example there were the interval is destroyed in 2 scenarios but probably you'll need to implement this case: $scope.$on('$destroy', function() {})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.