javascript - How is this setTimeout working? what is 49221 and how is console.log.bind working? -


this question has answer here:

how settimeout working? 49221 , how console.log.bind working?

for(var = 0; < 10; i++) {   settimeout(console.log.bind(console, i), 0); } 

output

49221

0

1

2

3

4

5

6

7

8

9

the fact you're seeing number before 0 tells me you're pasting browser console. you're seeing number because it's handle of last timer created in loop. for loop (this may surprise many reading this, did me when first learned of it) result in return value of last statement executed in last execution of body block. in case, that's return value of settimeout, number: handle you'd use if wanted cancel timer. (the spec's bit hard follow, it's in §13.7.4.7.)

the reason goes on show 0 through 9 schedules 10 timed callbacks console.log, creating bound functions via function#bind. each of functions, when called, turn around , call console.log this referring console , passing along argument given (i).

hence: if paste console, you'll see last timer handle followed 0 through 9.


about "for has result" thing, try in browser console:

for (var = 0 ; < 5; ++i) {     i; } 

you'll see 4 in console. :-)


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -