Maximiliano Maximiliano - 2 months ago 8
Javascript Question

javascript w/ jquery loop

im having a problem with my code, i have to make a loop, that each it loops, have to change add a class/change the color of something for just a while. i tried with a for and it didnt work, then i tried something like a loop using setinterval and it works better but still have something that is not working, it just adds the class/or toggle in that case first 1 element, and then maybe 2, then 3,etc and not 1 by 1 thanks

function runp(patron){
var x = 0;
var intervalID = setInterval(function () {
$("#container"+patron[x]).toggle(1).delay(1000).toggle(1).delay(1000);
if (++x === 20) {
window.clearInterval(intervalID);
}
}, 2000);
}


this is what i have: https://jsfiddle.net/dt8kxebg/
and this is what im trying to replicate: https://jsfiddle.net/jf0opams/

Answer

I think your problem is that you execute the runp() several times, because it is inside of a for loop. You should rather invoke the function just once after the loop, when your patron[] array is filled with random numbers (1-4).

The problem happens, because the for loop is super fast (few millisecs) filling your array with 20 random numbers. So you have invoked the animation/toggling function 20 times. This on/off behaviour takes 2 seconds and happens 20 times almost at the same time. You can see in my code in the browser console what the console.log() output to understand the behaviour better.

function start(patron, patronl){    
  while (patron.length<20){
    patron.push(rand(1,4));
    console.log('start: '+patron.length);
    //runp(patron, patron.length);//old place
    //readp(patron,//
  }   
  runp(patron);//new place
}

function runp(patron, iteration){
  var x = 0;
  var intervalID = setInterval(function () {
     $("#container"+patron[x]).toggle(1).delay(1000).toggle(1).delay(1000);

     //see how 20 outputs come at once, if runp() is inside for loop
     console.log('togglewait: '+x, 'start: '+iteration);       

     if (++x === 20) {
         window.clearInterval(intervalID);
     }
  }, 2000);
}