It is a little confusing with this code - why is the figure 5 displayed inside the squares, not the consecutive 0..4?

There is a version:
- the cycle is run much faster, and until the first setTimeout is executed, the counter has already reached the maximum value.

$(function() { for (var i = 0; i < 5; i++) { setTimeout(function() { $('.rows').append('<div>' + i + '</div>'); }, 800 * i); $('.res').text($('.res').text() + " " + i); } }); 
 .rows > div { width: 50px; height: 50px; background-color: #3c3; margin: 5px; float: left; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="rows"> <div></div> </div> <div class="res"></div> 

Reported as a duplicate at Grundy. javascript 18 Jul '17 at 10:14 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    Since the call to setTimeout not stop execution, but simply schedules the function call, the loop is executed all at once.
    So at the last iteration:

    i value = 4.
    i++ is called, the value is already 5
    checking the conditions of the cycle i < 5
    exit loop.

    Thus, after the end of the cycle, the value of the variable is 5.

    Next, the functions scheduled with setTimeout begin to run.

     function() { $('.rows').append('<div>' + i + '</div>'); } 

    Since the value of i is 5, then 5 is displayed.

    the loop is run much faster, and until the first setTimeout is executed

    Invalid guess. Since the JavaScript is executed in one thread, the execution of the function cannot be interrupted. That is, regardless of the interval value specified in the timeout, the entire cycle and the rest of the function will be executed first and only then, if there is nothing in the queue, the delayed function will be executed.

    • Yes, yes, I figured out the last iteration right after asking the question. - Jean-Claude
    • And if for () is inside for ()? The first is interrupted or not until the nested for () is executed? - Jean-Claude
    • @ Jean-Claude, the execution is strictly sequential. An ordinary single-threaded program. - Grundy
    • @ Jean-Claude, by the way, didn’t quite understand how the first for can break if the nested is executed inside it - Grundy
    • yes, I chose words from the answer) and what other functions are there that plan to call functions? - Jean-Claude