Tom
Tom

Reputation: 1263

setInterval in for loop

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);
}

Upvotes: 0

Views: 406

Answers (2)

brso05
brso05

Reputation: 13222

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.

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

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.

Upvotes: 0

Related Questions