Bringing setTimeout to ECMAScript

Peter van der Zee ecma at
Sat Mar 19 13:34:41 PDT 2011

On Sat, Mar 19, 2011 at 2:49 PM, Breton Slivka <zen at> wrote:

> never write code on no sleep.
> that code sample should be :
>  timers= (function () {
>     var timers = [];
>     var id=0;
>     timer=function (f,t) {
>          timers.push({func:f, interval:t, id:id++});
>          return id;
>     }
>    return timers;
>  })
>  runScript("env.js");
>  runScript("program.js");
>  ev=getEvents();
> while (!programHasQuit()) {
>  handleEvents(timers,ev);
> }

Actually, you're right. The timer family can be abstracted like this. I
don't think it would be as convenient as the current setTimeout and
setInterval because it kind of requires your code to use an architecture
that can work with an (explicit) event loop. But that's not necessarily a

So the only thing missing from this picture is a way to yield to the host
environment. In a single thread environment (like node or the browser), you
can't indefinitely loop because you'll lock up the host environment. So if
there was some way of yielding to the host environment, I think the problem
is solved. Not saying that such a mechanism is that trivial, but I do
believe that's a missing key to building timers in the language since you
currently can't yield, without timers :)

And re: return value. Some scripts might rely on the fact that the timers
return a number (an int, even). So if backwards compat is important (and it
always is), you can't really break with `typeof token == 'number'`. So if
there was a new native type, typeof would still have to return 'number',
which is not very desirable (null anyone?...). Also, given that setTimeout
and setInterval are already implemented in browsers for a while with
returning numbers, is it really still a problem we need to solve? Will
browsers really start implementing a setTimeout that returns a special timer
object? I think any implementation that uses "setTimeout" and "setInterval"
would have to mimic the current behavior in the browser...

(Even if we implement a host-environment yield kind of thing, I'd still
prefer a built-in setTimeout abstraction built on it for convience. But I
don't know about the security or whatever involved.)

Kyle: If there was a way to determine which timers are currently queued,
would that solve your problem? That's probably the only thing I'm missing
right now from the timer api: Some array with all queued timeouts/intervals.
Maybe that's to prevent the clear "attack" mentioned before, looping all
numbers and clearing them. I don't know. But if you had such an array
(either with just ints, or even an object with {int,time/interval,callback})
would that suffice for you? You could check the list and block while there
are timers left.

- peter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list