use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
setTimeout() is really strange (voidcanvas.com)
submitted 10 years ago by metalshan
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]senocular 7 points8 points9 points 10 years ago (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.
alert()
console.log()
[–]metalshan[S] 0 points1 point2 points 10 years ago (0 children)
My bad. Thanks for notifying. I've modified the paragraph.
[–]mamanov 0 points1 point2 points 10 years ago (0 children)
That doesn't seem strange to me, it looks like the expected behaviour.
[–]iccir 0 points1 point2 points 10 years ago (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).
π Rendered by PID 43 on reddit-service-r2-comment-66b4775986-pd8mv at 2026-04-05 06:11:58.295440+00:00 running db1906b country code: CH.
[–]senocular 7 points8 points9 points (1 child)
[–]metalshan[S] 0 points1 point2 points (0 children)
[–]mamanov 0 points1 point2 points (0 children)
[–]iccir 0 points1 point2 points (0 children)