setTimeout does not work with For in javascript [duplicate]

0

I'm starting in the javascript world and I'm having a question that kills my logic. I want a method to repeat a number of times every time, but not working when using the For loop, can you help me understand it please?

var repetirFunc = function(){
  for (var i = 1; i <= 11; i++){
    setTimeout(function(){
      console.log('Texto');
    }, 2000);
  }
}


repetirFunc();

In the above example I would like the "text" to repeat 11 times every 2 seconds, but it takes only 2 seconds for the first loop, after which it launches all the repetitions on the screen.

Image 1: The first 2 seconds stays like this

Image2:Afterthefirst2seconds,itlaunchesthe11repetitionsatonce

Thank you

    
asked by anonymous 22.09.2016 / 18:08

2 answers

2

The code is doing exactly what it was asked to do. You register a function in setTimeout and informs you that by 2000 milliseconds that function must be triggered. Note that when you call the setTimeout method the code continues to run normally, it does not wait 2000 milliseconds to continue. This is actually the reason for setTimeout to leave your code asynchronous so that in idle time JavaScript can work with other things.

You'll have to use another solution for your problem, one of them might be to use setInterval with a variable control.

var repetirFunc = function(empresa){
  var limite = 11;
  var i = 0;

  var intervalId = setInterval(function() {
    if (i++ > 11) return clearInterval(intervalId);

    console.log('Texto');
  }, 2000);
}


repetirFunc();

If you want to keep using setTimeout , you can calculate the milliseconds in each iteration.

var repetirFunc = function(empresa){
  for (var i = 1; i <= 11; i++){
    setTimeout(function(){
      console.log('Texto');
    }, 2000 * i);
  }
}


repetirFunc();
    
22.09.2016 / 18:19
-1

I believe that what you are looking for is setInterval and not setTimeout .

  • setInterval: Will run once every 2 seconds;
  • setTimeout: You will wait 2 seconds to run the entire code;

Try the following code:

var repetirFunc = function(empresa){
    for (var i = 1; i <= 11; i++){
        setInterval(function(){
            console.log('Texto');
        }, 2000);
    }
}
    
22.09.2016 / 18:18