Danman06
Danman06

Reputation: 69

AngularJS $timeout within for loop

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);

Upvotes: 0

Views: 1132

Answers (1)

pedrommuller
pedrommuller

Reputation: 16066

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

Upvotes: 2

Related Questions