Home javascript settimeout in the cycle

settimeout in the cycle




As I understand it, SetTimeout launches functions through the time you need.
Those. In the cycle, each iteration is delayed on our Timeout.

based on this knowledge question:
Why does it work as intended only the first iteration of the cycle and how to fix?

for (var i = 0; i & lt; 10; i ++) {
  setTimeout (Function () {Console.log ("sample");}, 4000);

Most likely I misunderstood how to use Settimeout

Answer 1, Authority 100%

code almost simultaneously orders 10 timeouts. In your example, all of them – after 4 seconds. Here they are all 10 and will be performed almost simultaneously. In my, they are ordered through one, two, three, etc. Seconds.

for (var i = 0; i & lt; 10; i ++) {
 setTimeout (Function () {Console.log ("sample");}, 1000 * (i + 1));

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions