Vasko Vasko - 5 months ago 10
Javascript Question

Printing array element every second

I know it sounds simple to most of you but it has been bugging me for a while now. I've been trying to loop through an array and its elements every second and do a function with the element being called out. But the result is always the loop printing all the elements at once.

This is what my code looks like. Sorry if its messy.

var ticking = window.setInterval(ticks, 1000);

function ticks() {
var morse = ['.', '-', '-', '-', '-'];

for (i = 0; morse.length > i; i++) {
if (morse[i] == '.') {
tickArrowDegree = 516;
$('#tick-arrow').css({'transform': 'rotate(' + tickArrowDegree + 'deg)'});

setTimeout(function reset() {
$('#tick-arrow').css({'transform': 'rotate(' + startPoint + 'deg)'});
}, 500);
}
else {
tickArrowDegree = 522;
$('#tick-arrow').css({'transform': 'rotate(' + tickArrowDegree + 'deg)'});

setTimeout(function reset() {
$('#tick-arrow').css({'transform': 'rotate(' + startPoint + 'deg)'});
}, 500);
}
}
}

Answer

Well, yes. You are saying you want to run that function every second. What happens in that function? You run through the whole array.

You probably want something like this. Just remove the for loop altogether and declare your iterator (i) outside the loop. https://jsfiddle.net/t82m8xog/

var ticking = window.setInterval(ticks, 1000);
var i = 0;
var startPoint=0;

function ticks() {
  var morse = ['.', '-', '-', '-', '-'];
  if (i >= morse.length) {
    clearInterval(ticking);    
    return;
  }

  if (morse[i] == '.') {
    tickArrowDegree = 516;
    $('#tick-arrow').css({
      'transform': 'rotate(' + tickArrowDegree + 'deg)'
    });

    setTimeout(function reset() {
      $('#tick-arrow').css({
        'transform': 'rotate(' + startPoint + 'deg)'
      });
    }, 500);
  } else {
    tickArrowDegree = 522;
    $('#tick-arrow').css({
      'transform': 'rotate(' + tickArrowDegree + 'deg)'
    });

    setTimeout(function reset() {
      $('#tick-arrow').css({
        'transform': 'rotate(' + startPoint + 'deg)'
      });
    }, 500);    
  }
  i++;
 }
Comments