Bringing setTimeout to ECMAScript

Kyle Simpson getify at gmail.com
Sat Mar 19 17:21:35 PDT 2011


>>> * No clamping. Time runs as fast as the platform lets it run.
>>> * The return value is not an integer but a unique unforgeable object for 
>>> canceling the event. No one without
>>> that object can cancel that event.
>>
>> This last point is something I was about to raise when starting to think 
>> about extending the Q API.
>> setTimeout returns a number, so a malicious could loop through numbers 
>> and call clearTimeout on them. An
>> unforgeable object sounds like the correct response to this issue. Have 
>> you considered wrapping
>> setTimeout&friends in SES with this solution? It wouldn't break code 
>> which do not rely on the returned value
>> being a number (but would break code which does, of course).
>
> Caja does exactly this. So far we haven't found any code that this 
> actually breaks. All uses we've encountered[1]
> treat the return value of setTimeout/setInterval as simply something they 
> can remember and later pass to
> clearTimeout/clearInterval.
>
> [1] That I'm aware of. Caja users should speak up if they've hit a 
> counter-example. Or anyone else that has seen
> code in the wild that actually counts on these values being numbers.

I have a number of different projects where I've used timers (mostly 
intervals rather than timeouts), where the logic that I used relied on being 
able to tell if a value was falsy or not, to know if there's a timer 
attached to some variable (so that you only set the interval once, and not 
multiple times).

So, for instance, a variable like foo = false`, when an interval is set, 
`foo = setInterval(...)`, and when that interval is cleared, I not only call 
`clearInterval(foo)` but I also call `foo = false` again to signal that the 
interval has been cleared (there is no `checkInterval(foo)` API to check 
this). Then, the next time I want to set the interval, I first check to see 
if `foo` is truthy or falsy, and only set if it's indeed falsy. So, all this 
is to say, I rely in those tests on whether the value is truthy or falsy. 
Not exactly relying on its data type, but it's important not to assume that 
noone ever checks those values -- in many cases, I do.



--Kyle




More information about the es-discuss mailing list