perfect-time

A generic clock that makes it easy to schedule repeating time based events with precision in Typescript. It works by calling scheduled events slightly before their side effects should take place, which is great in combination with Web Audio for example.

Usage no npm install needed!

<script type="module">
  import perfectTime from 'https://cdn.skypack.dev/perfect-time';
</script>

README

perfect-time

A generic clock that makes it easy to schedule repeating time based events with precision in Typescript. It works by calling scheduled events slightly before their side effects should take place, which is great in combination with Web Audio for example.

This essentially allows you to circumvent issues with javascript timers.

Get started

Install

yarn add perfect-time
# or
npm install --save perfect-time

Use

import { createClock, createSetIntervalTicker } from 'perfect-time'

// Any object with updating currentTime will do (make sure it is resumed)
const context = new AudioContext()

const clock = createClock({
  context,
  // The ticker is what periodically runs the check for events.
  // Ideally you would use a ticker in another thread but here
  // we tick on the same thread every 100ms using setInterval.
  ticker: createSetIntervalTicker(100),
})

clock.start()

clock
  .every(1, (event) => {
    // AudioContext.currentTime is in seconds
    console.log('every second:', event.count)
  })
  .limit(10) // clear event after 10 times!

API

The clock works with user or library provided "tickers" that can run on a separate thread. The events have a time tolerance in which they must get executed or else they get dropped. You can tweak the early and late tolerance to suit your application.

  • Early: too high and there might be a noticeable lag between state is reflected in the side effects (say a knob move to cause a change in sound).
  • Late: too high and events might actually start getting executed past their deadline.

Note that AudioContext is used just for the sake of the examples as the clock is generic and can work with any { currentTime: number }.

Create a clock

import { createClock, createScriptProcessorTicker } from 'perfect-time'

const clock = createClock({
  // For audio you'll want to pass AudioContext.
  context: audioContext,
  // This one actually needs to receive an AudioContext as it uses ScriptProcessorNode internally
  ticker: createScriptProcessorTicker(context),
})

Schedule Events

const callback = (event) => {
  // use event.time to schedule precisely (for example using AudioContext)
  oscNode.start(event.time)
}

// callback gets called right before context.currentTime reaches 10 seconds
clock.atTime(10, callback)

// callback gets called immediately and and repeats every 10 seconds
clock.every(10, callback)

// callback gets called right before 10 seconds elapsed
clock.setTimeout(10, callback)

// callback gets called right before 10 seconds elapsed and repeats
clock.setInterval(10, callback)

Control Events

You can also control the event directly, for example to schedule repetition in the future or limiting repeats.

// callback called right before context.currentTime reaches 10, and then every second 3 times
// clock.atTime returns an event, which we call .repeat on
clock.atTime(10, callback).repeat(1, 3)

// equivalent to the above
clock
  .atTime(10, callback)
  .repeat(1)
  .limit(3)

Cancel Events

// start an oscillator node at context.currentTime = 1
const event = clock.every(1, (event) => {
  oscNode.start(event.time)
})

// nevermind
event.clear()

Change speed of a group of events

const eventA = clock.atTime(1, () => console.log('event A')).repeat(3)
const eventB = clock.atTime(2, () => console.log('event B')).repeat(3)
const eventC = clock.atTime(3, () => console.log('event C')).repeat(3)

// the speed will be halved immediately for all events
clock.timeStretch(0.5)

// the speed will be doubled in 9 seconds only for eventA and eventB
clock.setTimeout(9, (event) => {
  clock.timeStretch(2, event.time, [eventA, eventB])
})

Examples