preact-cycle icon indicating copy to clipboard operation
preact-cycle copied to clipboard

setTimeout vs. requestAnimationFrame?

Open matthewmueller opened this issue 9 years ago • 2 comments

hey just wondering if there was any reason you went with a setTimeout in the renderer here? just out of simplicity?

I'm thinking requestAnimationFrame might be a bit better (to render on the paints) but i'm not sure if setTimeout was a deliberate decision or not.

matthewmueller avatar Mar 04 '16 05:03 matthewmueller

It was definitely just for simplicity. Technically there isn't a real reason to debounce rendering at all in preact-cycle, so it could just be made synchronous. I think my original intent with the setTimeout was to support animation (since the frame delay is done for you, you just have to call the next mutation in order to ask for another frame. If that's the only real use-case though, you're right in thinking requestAnimationFrame would be a better fit.

Some context: Preact itself originally used setTimeout(0), but switched to requestAnimationFrame() in 3.x. In 4.x it tries to use the DOM for tight async but falls back to setTimeout: https://github.com/developit/preact/blob/master/src/util.js#L125-L137 There is also an option to turn off async altogether (options.syncComponentUpdates=true), which might be worth honoring here too.

developit avatar Mar 04 '16 13:03 developit

Just FYI requestAnimationFrame is not triggered if tab is not visible. setTimeout(0) has about 4ms delay in modern browsers (it was about 15ms in old). Also setTimeout "slows down" in invisible tab.

Alternatives:

  • https://github.com/YuzuJS/setImmediate
  • https://github.com/kriskowal/asap

To read more: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

stereobooster avatar May 29 '17 12:05 stereobooster