javascript - tricky setTimeout sequence -


set of settimeout calls intervals 0,1,2,3.

function f() {        settimeout(function a() {console.log(10);}, 3);        settimeout(function b() {console.log(20);}, 2);        settimeout(function c() {console.log(30);}, 1);        settimeout(function d() {console.log(40);}, 0);    }    f();

output: (from chrome. hope same in other browsers)

30

40

20

10

can explain why ordering not 30, 40, 10, 20? said browsers maintain minimum 10ms or (spec says) 4ms interval. if so, validate output time metrics or whichever convenient explain behavior. minute detail missing understand awesome feature of language?

edited:

i know these functions asynchronous. , have read john resig' blog couple of times. , know settimeout' callback not guaranteed execute @ interval specified.

to more precise, expect explanation can explain behavior in terms of execution queue, event loop, call stacks , timers.

in order understand how timers work internally there’s 1 important concept needs explored: timer delay not guaranteed. since javascript in browser executes on single thread asynchronous events (such mouse clicks , timers) run when there’s been opening in execution.

refer this , this more details


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -