简体   繁体   中英

Return value from setTimeout() inside for loop

How could I make loop wait before setTimeout function is executed and I could modify its i value before making loop going again?

code:

 function Delay(){
            for (let i = headsPosition; i <= lineIndex.length-1; i++) {
                (function(i){
                    setTimeout(() => {
                    if (Number.isInteger(lineIndex[i])) {
                        let parsing = parseInt(lineIndex[i]);
                        lineIndex[i] = parsing.toString();
                    }
                    
                        for (let j = 1; j <= firstPosition.length; j++) {
                            if (currentState == firstPosition[j]){ 
                                if (lineIndex[i] == secondPosition[j]) {
                                    lineIndex[i] = thirdPosition[j];
                                    currentState = fifthPosition[j];
                                    tape.innerHTML = lineIndex;
                                    if (fourthPosition[j] === "L") {
                                        i-=2;
                                    }
                                    break;
                                }   
                            }
                        }   
                        console.log(i) 
                    }, i*100);
            })(i);
            console.log(i) 
            }
        }

        startButton.onclick = function (){
           Delay();
        }

You can achieve that by using a recursive function:

 function Delay() {
  loop(headsPosition, lineIndex.length-1);
 }
 
 function loop(i, maxi) {
   setTimeout(() => {
     if (Number.isInteger(lineIndex[i])) {
       let parsing = parseInt(lineIndex[i]);
       lineIndex[i] = parsing.toString();
     }

     for (let j = 1; j <= firstPosition.length; j++) {
       if (currentState == firstPosition[j]) {
         if (lineIndex[i] == secondPosition[j]) {
           lineIndex[i] = thirdPosition[j];
           currentState = fifthPosition[j];
           tape.innerHTML = lineIndex;
           if (fourthPosition[j] === "L") {
             i -= 2;
           }
           break;
         }
       }
     }
     console.log(i)
     
     //this part is what makes it behave like a loop
     if(i < maxi) {
        loop(i + 1, maxi);
     }
   }, i * 100);
 }

 startButton.onclick = function() {
   Delay();
 };

Instead of using a for loop (which does not wait), you create a function that, when it gets to the end, calls itself with the next value of i (up to a given limit). This allows you to wait for setTimeout within the function. It also allows you to modify the value of i based on your own set of conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM