Skip to content Skip to sidebar Skip to footer

Javascript Timeout - Specification

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

Solution 1:

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 the setTimeout 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:

  1. Run the oldest task on one of the event loop's task queues, ignoring tasks whose associated Documents are not fully active [...]

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:

Can we be sure that on all major browsers the code of the timeout is done after the code handling the first user action. This independently of the delay time.

... 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.

Post a Comment for "Javascript Timeout - Specification"