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.
Comments
Post a Comment