help with for loop, with variable approaching 100

0

I'm doing a work with images and I have the code below:

var tempoTransicao = 5;
var quantasImagens = $("ul.slider li img").size();
var tamanhoIntervalos = Math.round(100/quantasImagens);
var t = 0;

for (i = 1; i <= quantasImagens; i++) {                              
    tMin = t + tempoTransicao;
    tMax = t + tamanhoIntervalos;    
    t+=tamanhoIntervalos;
    //if(t=~100) i=quantasImagens;
    alert("tMin: "+tMin);
    alert("tMax: "+tMax);
    alert("t: "+t);
}

The idea is a for loop running from 0 to 100%, filling frames with tamanhoIntervalos % . Everything works fine, but I need to figure out a way to get on the last loop, do i=quantasImagens .

That's where my difficulty is, because in the last iteration almost never the variable tMax will receive 100% value.

I also tried the variable i iterating from 0 to 100%:

for (i = 0; i <= 100; i++) {
                    
    tMin = i + tempoTransicao;
    tMax = i + tamanhoIntervalos;          
    if (i == 0 ) {
        tMin = 0;
    } else if  (i == 100) {
        //tMax = 100;
    }      
    
    //alert("tempoTransicao: "+tempoTransicao);
    //alert("tMin: "+tMin);
    //alert("tMax: "+tMax);
    
    i = tMax==100 ? 100 : tMax-1;
    
}

HTML

 <ul class="slider">
    <li> 
      <img src="_imgs/_slideShow/1.png" /> 
      <img src="_imgs/_slideShow/2.png" /> 
      <img src="_imgs/_slideShow/3.png" /> 
     </li>
  </ul>

Does anyone help me find this logic?

    
asked by anonymous 24.10.2017 / 18:21

1 answer

1

To identify the last iteration in the loop, you just need to check the value of your control variable. In its case, the control variable is i and varies from 0 to quantasImagens , so when it has the same value of quantasImagens it will be the last iteration of the loop:

var tempoTransicao = 5;
var quantasImagens = $("ul.slider li img").size();
var tamanhoIntervalos = Math.round(100/quantasImagens);
var t = 0;

for (i = 1; i <= quantasImagens; i++) {                              
    tMin = t + tempoTransicao;
    tMax = t + tamanhoIntervalos;    
    t+=tamanhoIntervalos;
    //if(t=~100) i=quantasImagens;
    alert("tMin: "+tMin);
    alert("tMax: "+tMax);
    alert("t: "+t);

    if (i == quantasImagens) {
        // Faça algo na última iteração...
    }
}

See a simple example:

for(let i = 0; i <= 5; i++) {
    console.log(i);
    
    if (i == 5) {
        console.log("Terminou");
    }
}
    
24.10.2017 / 18:37