Search code examples
javascripthtmlweb-audio-api

Do Web Audio API events run in a separate thread?


I'm particularly interested in the onaudioprocess of the ScriptProcessorNode (until recently called JavaScriptNode). It is an event listener which is called periodically for audio processing. Does it run in a separate thread?

I'd want to feed the data to a circular buffer and process it outside of this callback so I don't hog the CPU. I can use web workers for the async processing, but AFAIK I'd need a different implementation of the ring buffer in the case of different threads.

Is there a way to test this?


Solution

  • All JavaScript is single-threaded, synchronously executed. Any asynchronous stuff is done via events, which add their handlers to the task queue - to be executed when the current task is finished.

    To use separate threads, you would need an environment like WebWorkers - every thread has its own execution context (global scope) and task queue; communication between them is done via events.

    As the onaudioprocess handler seems to live in the same scope as the DOM, it is quite unlikely that it runs in its own thread. If you really have a computationally intensive task that makes your page unresponsive, you should use a WebWorker into which you feed the audio events:

    myScriptProcessorNode.onaudioprocess = myWebWorker.postMessage;