Bringing setTimeout to ECMAScript

Wes Garland wes at
Sat Mar 19 12:34:22 PDT 2011

On Sat, Mar 19, 2011 at 12:58 PM, Mark S. Miller <erights at> wrote:

> The idea is not stupid at all. It's perfectly sound. For example, the delay
> example you noticed could be made primitive and setTimeout built out of
> that. Either can be built from the other. The advantage of layering
> setTimeout on a new primitive, whether delay or <
>> or something
> else, is that the new primitive can avoid spec weirdnesses already
> entrenched for setTimeout, like this 4ms clamping. Instead, this 4ms
> weirdness could just be specifically part of setTimeout's behavior.

I agree 100% - there is no requirement to make setTimeout a fundamental
building blocking; it can easily be treated as a high-level API. There is
also no need to make the base time measurement unit milliseconds -- it is
very easy to see a future where microsecond- or even nanosecond-resolution
is desirable.  (Assuming, of course, we manage to get over the current GHz
barrier to make our individual cores faster).

A base specification built on nanosecond-resolution timers gives us a
maximal timeout of 104 days with 53-bit "integers".

That said, I have to ask: is there a reason the base specification needs to
discuss time at all?  Why not just a function that returns true or false?
This still allows us to implement setTimeout in terms of Date, probably
requires less specification, and adds more power  ("is a mouse button
down?"  vs.  "is it 4 o'clock?")

In this untested example which implements setTimeout, I present a function
called enqueue, which takes as it's argument a function that returns true if
the function is to be re-interested at the end of the event queue once it
was evaluated:

function setTimeout(f, delay) {
  var when = +(new Date()) + delay;
  enqueue(function() {
    if (+(new Date()) < when)
      return true;
    if (typeof f === "string"))

Of course, we could make this a little cheaper by codifying moz's, or even having a property of the event system which is the value
of the timestamp when the current iteration of the event loop began.

In the past, a timer-specific low-level interface may have been desirable
from an implementation point of view. I don't believe this the case any
more, given two factors -- modern JS engines are really fast at this stuff,
and we are not going to be doing any kind of pre-emptive timer (so alarm()-,
setitimer()-, etc-backed implementations are unnecessary).

I really think if we're looking at setTimeout() we should be looking at
arbitrary condition evaluation in the event loop.  The embedders will be
able to fill in the blanks, and I bet most browser vendors are pretty much
already there.


Wesley W. Garland
Director, Product Development
PageMail, Inc.
+1 613 542 2787 x 102
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list