This is more than a question, it is a request to ensure the Quality of Service (QoS) of Javascript's timeout function.
Looking at the following pseudo-code:
.. start something in JS after a user action
.. some js code
setTimeout( function() { doSomething }, 1 );
.. continue for longer than 1ms doing something
.. end code for user action
.. after
.. execute doSomething
Can we be sure that on all major browsers, the code of the timeout is done after the code has handled the first user action? This is independent of the delay time.
The delay time is not important, rather the fact 'doSomething' code is executed after.
What happens with 0 delay?
Thanks in advance for your experience on different browsers.
When an asynchronous event "fires" is different from when it actually executes, due to Javascript's single-threaded nature.
Each block of code being evaluated is represented internally as a task in a task queue. So let's say that in the middle of a given block of code, an asynchronous event is prepped for execution via
setTimeout()
. If the delay is short enough, in practice nothing's stopping it from "firing" before the rest of that same block of code is finished executing. However "firing" doesn't mean that thesetTimeout
handler actually interrupts and executes. It just means that it's turned into a task on a task queue. Actual execution still has to wait until it is popped off of the task queue, and that can't happen until the original block of code is finished.Here's an HTML5 spec snippet that, while not authoritative for all browsers of course, being HTML5, is illustrative:
http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#processing-model-3
The first of 7 steps defined there for the main event loop is:
Note that this first step is atomic. The task must run to completion before the environment is reset and the next task is picked up.
Also have a look at John Resig's post on this: http://ejohn.org/blog/how-javascript-timers-work/
So, wrt your question:
... the answer is yes, we can be sure. (In the vanilla case... I assume we're only talking about the traditional single/UI thread, and not talking about processing by Web Workers).
Also, although you did mention that you don't care as much about the delay time per se, still you may be interested to note the "clamp time" (enforced minimum delay) as well, which appears to be de facto standardized at around 4ms.