[whatwg] Polling APIs in JavaScript vs Callbacks

Garrett Smith dhtmlkitchen at gmail.com
Mon Feb 11 22:56:52 PST 2013


On 2/9/13, Glenn Maynard <glenn at zewt.org> wrote:
> On Sat, Feb 9, 2013 at 10:43 AM, Tab Atkins Jr.
> <jackalmage at gmail.com>wrote:
>
>> That said, there *are* still some isolated use-cases for polling.  ^_^
>>  When an event-based approach would potentially deliver far too many
>> events, with separation between them perhaps less than 1ms, exposing a
>> polling-based API instead can be useful.  I haven't followed the
>> Gamepad API lately, but I know this was at least considered for some
>> of the types of feedback, such as the exact position of joysticks or
>> pressure on buttons, both of which can change very rapidly in
>> realistic scenarios.
>>
>
> A polling API doesn't help you there, since you can't poll every 1ms in
> script (certainly not in the UI thread, and probably not reliably even in a
> worker).  In fact, since setTimeout will be throttled but events fired by
> the browser don't have to be, events can be sent faster than you can poll
> in the UI thread (though this is probably a bad idea most of the time).
>
> The solution is probably a matter of buffering the changes, and limiting
> how frequently "something was buffered" events fire.
Are you proposing event quantization threshold?


That type of solution can work for handling the situation where the
event fires too many times like resize and mousemove events. But it is
a little cumbersome to write out event throttlers by hand.

The MOUSE_MOVE_THRESHOLD is no phenomenon really, but useful in such
situations and I'm not boasting at all. Here is the explanation of my
idea which I started using around 2007, IIRC:
http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/bc5274b75820e5ff/96fbac718201ebbf?pli=1

Anyway, if the idea is to set an event quantization threshold, it
should be done at the time of registering the callback. And I see no
good reason why that should be modifiable. A hypothetical a 'quant'
property example (it can't be expected to work, just trying to sketch
out the idea).

 var listener = {
  handleEvent : function(ev) { console.log(ev); },
  quant : 40
 };
//  or even
 function handleEvent (ev) { console.log(ev); }
 handleEvent.quant = 40;

 var booleanParametersSuck = false;

 document.addEventListener("mousemove",  listener, booleanParametersSuck);

That way, you can get
> low-latency, high-time-resolution data if you want it, by reading all a
> list of changes made since the last event, without trying to poll at 1kHz
> in script.  (I have a vague recollection of proposing exactly this, but I
> don't think it went anywhere and I haven't seen any discussion about the
> gamepad API here or on -webapps in a long time.)
>
Planck time is the smallest unit of time. Where does it go?
-- 
Garrett
Twitter: @xkit
personx.tumblr.com



More information about the whatwg mailing list