search

Home  >  Q&A  >  body text

How to use js setTimeout in double for loop?

Numbers that are not printed in the log also take up time. Why and how to solve it?

<script>
function resort(){
    for (let i = 0; i < 10; i++) {
        for (let j = 0; j < 10 - i; j++) {
            setTimeout(function(){
                console.log(i*10 + j);
            },(i*10+j)*500);
        };
    };
}
resort();
</script>
代言代言2788 days ago995

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-06-26 10:56:17

    What do you want to express?

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-26 10:56:17

    It is also the same as the closure in the for loop, wrapping a layer on the outside to execute the function immediately

    function resort(){
        for (let i = 0; i < 10; i++) {
            for (let j = 0; j < 10 - i; j++) {
              (function(a,b){
                setTimeout(function(){
                    console.log(a*10 + b);
                },(a*10+b)*500);
              })(i,j)
            };
        };
    }
    resort();

    I don’t know if this is what it means

    reply
    0
  • Cancelreply