3

I'm trying to put a delay in a forEach loop in AngularJS. With $timeout, they're firing once at the same time. With $interval, they're caught in an infinite loop, again at the same time.

I need the function delay between iterations of the forEach loop to fire the animations in delayed succession rather than at the same time.

...
vm.questions = [
    {correct:false,animateDemo:false},
    {correct:true,animateDemo:false}, 
    {correct:true,animateDemo:false}
];

vm.questions.forEach(function(question, idx) {
    // need a delay between animationDemo assignments
    $timeout(function(){
      if (question.correct) {
        question.animateDemo = true;
      }
    },1000);
  });

I tried interval too, but that causes an infinite loop.

vm.questions = [{correct:false}. {correct:true}, {correct:true}];


vm.questions.forEach(function(question, idx) {
    // causes infinite loop
    $interval(function(){
      if (question.correct) {
        question.animateDemo = true;
      }
    },1000);
  });

I'm sure the solution is probably something simple, but getting it in this syntax is a bit confusing to me personally.

1 Answer 1

1

What you can do is have a dynamic timeout for each question animation.

Something like this:

var timeoutTimer = 1000;
vm.questions.forEach(function(question, idx) {
    $timeout(function(){
      if (question.correct) {
        question.animateDemo = true;
      }
    }, timeoutTimer);
    timeoutTimer += 1000;
  });

You want to use $timeout and not $interval since you only want each animation to trigger once. $interval will execute every x seconds until you cancel it.

$timeout is a promise so code will continue to execute while it waits for the delay. This is why it appears they are all firing at the same time. They actually are probably a few nanoseconds apart from each other.

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

Comments

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.