0

I'm writing a function which will iterate through an array with some time interval.

eg:arr=[1,2,3,4,5,6,7]

And I want to show each element with angular interval.

$interval(step,5000,7);
function step(i){
    console.log(arr[i]);
}

So it'll output the numbers inside the array in a 5 seconds' interval. How can I pass the parameter into the function? Thanks.

0

4 Answers 4

1

You could also do this way:

var arrOrig =[1,2,3,4,5,6,7], 
    arr = angular.copy(arrOrig), //if you want it for later
    cancelPromise = $interval(step, 5000);

function step() {
  console.log(arr.shift()); //take out the item from top of array
  if (!arr.length) { //once array runs out
    $interval.cancel(cancelPromise); //cancel interval
  }
}

var arr = [1, 2, 3, 4, 5, 6, 7];
var $interval = angular.injector(['ng']).get('$interval');
var cancelPromise = $interval(step, 5000);

function step() {
  console.log(arr.shift());
  if (!arr.length) {
    $interval.cancel(cancelPromise);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

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

Comments

0
arr.forEach(function (number, idx) {
    $timeout(function () {
        console.log(number);
    }, 5000 * (idx + 1));
});

You want to use $timeout rather than $interval because calling $interval will set up an interval each time for each number and it won't stop until it's cleared explicitly.

3 Comments

I want to output 1,2,3,4,5,6,7 with 5 seconds interval each. And I've already specify the steps in the interval so it only iterate 7 times.
@Gabriel I see; you can still use my code to do this though: plnkr.co/edit/ywlowWztJiTaXfqHJNvu?p=preview
yes, your code work perfectly. I'm just wondering whether it works with interval
0
var i=0;
$interval(function(){
   step(i);
   i++
},5000);

function step(i){
    console.log(arr[i]);
}

Comments

0

This code will display the numbers one at a time, on repeat:

var getNextNumber = (function(){
    var i = 0;
    var numbers = [1,2,3,4,5,6,7];
    return function(){
        if(i >= numbers.length){
            i = 0;
        }
        return numbers[i++];
    };
})();

$interval(function(){
    var number = getNextNumber();
    console.log(number);
},5000);

See this working jsfiddle.

If you want to display them only once, use one of the $timeout solutions from one of the other answers. $interval is all about repeating some command for an indefinite amount of time, whereas $timeout is more about performing a command once in the future. See this answer for more.

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.