When an asynchronous event "fires" is different from when it is actually running, due to the single-threaded nature of Javascript.
Each block of the evaluated code is represented inside the task as a task in the task queue. So, let's say that in the middle of this block of code, an asynchronous event is prepared for execution through setTimeout() . If the delay is short enough, in practice, nothing stops, because it fires before the rest of the same block of code is completed. However, “shooting” does not mean that the setTimeout handler actually interrupts and executes. It just means that it has become a task in the task queue. Actual execution still needs to wait until it slips out of the task queue, and this cannot happen until the original code block is complete.
Here is a snippet of the HTML5 specification, which, although 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 for the main event loop is as follows:
- Launch an old task in one of the queues of the event cycle tasks , ignoring tasks, documents associated with them are not fully active [...]
Note that this first step is atomic. The task must complete before the environment is reset and the next task is raised.
Also see John Resig's post on this: http://ejohn.org/blog/how-javascript-timers-work/
So answer the question:
Is it possible to be sure that in all major browsers the timeout code is executed after processing the code by the first user action. This is independent of the delay time.
... the answer is yes, we can be sure. (In the case of vanilla ... I suppose we are talking only about the traditional single / user interface thread, not about processing by web workers). A.
In addition, although you already mentioned that you do not care about the delay time as such, you might also be interested to note the “clamping time” (forced minimum delay), which looks like de facto standardized for about 4 ms .