help with for loop, with variable approaching 100

Asked

Viewed 21 times

0

I am 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 bond for that passes in run from 0 to 100%, filling tables of  tamanhoIntervalos %. Everything works fine, but I need to figure out a way when I get to the last loop, do i=quantasImagens.

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

I also tried with 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>

Someone help me find that logic?

  • In the first for, to identify the last iteration you can do if (i == quantasImagens) { ... }

  • Can you help me with that question by doing me a favor? https://answall.com/questions/249014/crea-uma-anima%C3%A7%C3%A3o-com-jquery

1 answer

1


To identify the last iteration in the loop, just check the value of your control variable. In your case, the control variable is i and varies from 0 to quantasImagens, then when it possesses the same value as quantasImagens 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");
    }
}

  • Can you help me with that question by doing me a favor? https://answall.com/questions/249014/crea-uma-anima%C3%A7%C3%A3o-com-jquery

Browser other questions tagged

You are not signed in. Login or sign up in order to post.