audio-context-timers

A replacement for setInterval() and setTimeout() which works in unfocused windows.

Usage no npm install needed!

<script type="module">
  import audioContextTimers from 'https://cdn.skypack.dev/audio-context-timers';
</script>

README

audio-context-timers

A replacement for setInterval() and setTimeout() which works in unfocused windows.

dependencies version

Motivation

For scripts that rely on WindowTimers like setInterval() or setTimeout() things get confusing when the site which the script is running on loses focus. Chrome, Firefox and maybe others throttle the frequency of firing those timers to a maximum of once per second in such a situation. However it is possible to schedule AudioBufferSourceNodes and listen for their onended event to achieve a similar result. This makes it possible to avoid the throttling.

Getting Started

AudioContextTimers are available as a package on npm. Simply run the following command to install it:

npm install audio-context-timers

You can then require the audioContextTimers instance from within your code like this:

import * as audioContextTimers from 'audio-context-timers';

The usage is exactly the same as with the corresponding functions on the global scope.

var intervalId = audioContextTimers.setInterval(() => {
    // do something many times
}, 100);

audioContextTimers.clearInterval(intervalId);

var timeoutId = audioContextTimers.setTimeout(() => {
    // do something once
}, 100);

audioContextTimers.clearTimeout(timeoutId);

However there are some subtle differences between AudioContextTimers and WindowTimers which are basically the same those of the worker-timers package.