audio-context-timers
Version:
A replacement for setInterval() and setTimeout() which works in unfocused windows.
29 lines • 1.31 kB
JavaScript
export const createScheduleFunction = (callFunction, createAudioBuffer, createAudioBufferSourceNode, createMinimalAudioContext, performance) => {
let audioBuffer = null;
let minimalAudioContext = null;
const scheduleFunction = (id, delay, type) => {
const now = performance.now();
if (minimalAudioContext === null) {
minimalAudioContext = createMinimalAudioContext();
}
const { destination, sampleRate } = minimalAudioContext;
if (audioBuffer === null) {
audioBuffer = createAudioBuffer(2, sampleRate);
}
const audioBufferSourceNode = createAudioBufferSourceNode(minimalAudioContext, audioBuffer);
audioBufferSourceNode.onended = () => {
const elapsedTime = performance.now() - now;
if (elapsedTime >= delay) {
callFunction(id);
}
else {
scheduleFunction(id, delay - elapsedTime, type);
}
audioBufferSourceNode.disconnect(destination);
};
audioBufferSourceNode.connect(destination);
audioBufferSourceNode.start(Math.max(0, minimalAudioContext.currentTime + delay / 1000 - audioBuffer.duration));
};
return scheduleFunction;
};
//# sourceMappingURL=schedule-function.js.map