setTimeout does not work with For in javascript

Asked

Viewed 369 times

0

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

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


repetirFunc();

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

Image 1: The first 2 seconds is like this Os primeiros 2 segundo fica assim

Image 2: After the first 2 seconds, he throws you the 11 repetitions at once Depois dos primeiros 2 segundos, ele te lança as 11 repetições de uma só vez

thank you

2 answers

2


The code is doing exactly what it was asked to do. You record a function on setTimeout and informs that from here 2000 milliseconds this function must be fired. Note that when you call the method setTimeout the code continues running normally, it does not wait 2000 milliseconds to continue. That is actually why there is the setTimeout, to make your code asynchronous, so that in this idle time Javascript can work with other things.

You will need to use another solution to your problem, one of them may be the use of 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();
  • It worked Gabriel, thank you very much.

  • If you solved the problem (and you don’t need anything else), you can mark it as the correct answer... and nothing. ;)

-1

I believe what you’re looking for is setInterval and not the setTimeout.

  • setInterval: Will run 1 time every 2 seconds;
  • setTimeout: Will wait 2 seconds to run all the code;

Try the following code:

var repetirFunc = function(empresa){
    for (var i = 1; i <= 11; i++){
        setInterval(function(){
            console.log('Texto');
        }, 2000);
    }
}
  • You want to test the code you proposed, buddy?

  • So Celsom, gave the same result as the code I posted, because according to my logic, to each loop of the for() should be executed the function I am passing in setTimeout() and should take 2 seconds.

Browser other questions tagged

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