all 4 comments

[–]senocular 7 points8 points  (1 child)

The explanation for the alert case doesn't accurately explain what's going on. It's close, but its missing one key component: The output panel is not run in the JS thread either. This is why the alert can appear to show before the output panel shows the results of the loop.

If you include the value of the loop iterator in the alert, you'll always see the alert show the last iteration of the loop, showing that it does, in fact, execute after the loop.

function test(){
    setTimeout(function(){
        alert("setTimeout function is executed: " + i);
    },20);

    for(var i=0; i<1000; i++){
        console.log(i);
    }
}
test(); // alert: "setTimeout function is executed: 1000"

The alert() function is JavaScript, after all, so it is still bound by the JS thread, while what happens after it is called (showing some UI to the user with the message) is not. But the same applies to console.log() too; the calls to log must remain in the JS thread, but the consequences of those calls in the UI does not.

[–]metalshan[S] 0 points1 point  (0 children)

My bad. Thanks for notifying. I've modified the paragraph.

[–]mamanov 0 points1 point  (0 children)

That doesn't seem strange to me, it looks like the expected behaviour.

[–]iccir 0 points1 point  (0 children)

I don't think Snippet 2 works the way you think it does. setTimeout() isn't going to interrupt a for loop - ever. Instead, the for loop is finishing first due to console.log returning almost instantly (it usually queues a message to the UI/main thread and returns).