Search code examples
javascriptcanvasweb-audio-apirequestanimationframe

Handling events like clicks while using requestAnimationFrame loop


I'm using requestAnimationFrame in a project and I need to trigger certain audio and visual events based on user input. When I receive the input, I cache the information to be rendered during the next pass of requestAnimationFrame and I continue doing processing to render the audio event immediately.

My question is: could the processing of information for audio output delay the visual rendering and cause jank? For example, if...

  • a mouse click happens at timestamp 15ms;
  • the next pass of requestAnimationFrame is scheduled to occur at 16ms (so 1ms after the click); and
  • processing the mouse click for audio rendering takes 5ms;

will processing the mouse click for audio rendering, which will finish at timestamp 20ms, delay the execution of requestAnimationFrame by 5ms? Or does requestAnimationFrame run on a separate thread that is not effected by what's going on on the event loop?

Thanks!


Solution

  • No, requestAnimationFrame(rAF) doesn't work on an other thread, so yes, if you have a long task in the event loop, it will delay everything else happening in the event loop, including rAF. But don't worry, your rAF callback will also take some time to execute, if your click handler really takes only 1ms, it won't be noticeable.