Domanda

Alright, so i need to run a timeout inside of a loop without recalling the loop all over again. The inner loop NEEDS to be a timeout.

(function loaded() {
for(var i=0;i<100; i++){
  if(!SOMECONDITION){
     setTimeout(loaded, 1);
  }
}
})();

This code almost works perfect except that if the condition is not met, it recalls the entire loop. I need it to only recall inside the loop like this.. but its not working.

    for(var i=0;i<100; i++){
(function loaded(i) {
      if(!SOMECONDITION){
         setTimeout(loaded, 1);
      }
})(i);
    }

the variable i must be able to be passed in the loop.

È stato utile?

Soluzione

A bit complex, and someone might be able to simplify, but... I think you need two functions, one to capture i into a closure, one to have no arguments so it can be called as a timeout.

for (var i = 0; i < 100; i++) {
  (function(i) {
    function loaded() {
      if (!SOMECONDITION) {
        setTimeout(loaded, 1);
      }
    };
    loaded();
  })(i);
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top