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.

Gabriel
  • 601
  • 1
  • 10
  • 26

4 Answers4

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>
PSL
  • 123,204
  • 21
  • 253
  • 243
0
var i=0;
$interval(function(){
   step(i);
   i++
},5000);

function step(i){
    console.log(arr[i]);
}
user3227295
  • 2,168
  • 1
  • 11
  • 17
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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 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 May 19 '15 at 20:33
  • @Gabriel I see; you can still use my code to do this though: http://plnkr.co/edit/ywlowWztJiTaXfqHJNvu?p=preview – Explosion Pills May 19 '15 at 20:38
  • yes, your code work perfectly. I'm just wondering whether it works with interval – Gabriel May 19 '15 at 20:57
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.

Community
  • 1
  • 1
Jonathan Wilson
  • 4,138
  • 1
  • 24
  • 36