0

Here's what I'm attempting to do: add 1 new class name every 3 seconds and then stop after 5 have been added. When I run this code, it keeps adding classes indefinitely! It also adds 3 classes all at 1 time.

var linesOfText = ['Testing Second Part', 'Testing Third Part', 'Testing Fourth Part', 'Testing Fifth Part'];
var j = 1;
var total = 5;
for (var i = linesOfText.length - 1; i >= 0; i--) {

   var myVar = setInterval(function(){
      $('.vertical-effectOFF').addClass('vertical-effect-' + j);
      j++;
      if (j === total) {
        console.log('stop!');
        clearInterval(myVar);
      }
   }, 3000);
}
Tom
  • 1,215
  • 3
  • 19
  • 30

2 Answers2

1

Try taking out the for loop and changing j = 5 to j = 0:

var linesOfText = ['Testing Second Part', 'Testing Third Part', 'Testing Fourth Part', 'Testing Fifth Part'];
var j = 0;
var total = 5;
var myVar = setInterval(function(){
   $('.vertical-effectOFF').addClass('vertical-effect-' + j);
   j++;
   if (j === total) {
     console.log('stop!');
     clearInterval(myVar);
   }
}, 3000);

This will add a class every 3 seconds until 5 classes are added.

brso05
  • 13,142
  • 2
  • 21
  • 40
  • Is there a good way to add a setTimeout after the .addClass() line? I need to wait a few seconds, do something and then go to the j++ line. – Tom Jun 15 '15 at 19:05
  • @Tom check out this link http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep – brso05 Jun 15 '15 at 19:21
  • I have an extension of this question here: http://stackoverflow.com/questions/30873346/settimeout-within-setinterval-not-firing-as-expected – Tom Jun 16 '15 at 16:38
0

Using a for loop for this is not the best approach. It is not functioning as expected because it set 5 intervals immediately to all execute after 3 seconds. Just set the interval to call a named function and terminate it when j === total

var j = 1;
var total = 5;

var myVar = setInterval(intervalAddClass, 3000);

function intervalAddClass() {
    $('.vertical-effectOFF').addClass('vertical-effect-' + j);
    j++;
    if (j === total) {
        console.log('stop!');
        clearInterval(myVar);
    } 
}

Also, there is no need for linesOfText as you are not using it in your code.

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53