• Stars
    star
    566
  • Rank 78,516 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

logo

worker-timers

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

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 at which they invoke those timers to a maximum of once per second in such a situation. However this is only true for the main thread and does not affect the behavior of Web Workers. Therefore it is possible to avoid the throttling by using a worker to do the actual scheduling. This is exactly what worker-timers does.

Getting Started

worker-timers is available as a package on npm. Run the following command to install it:

npm install worker-timers

You can then import the exported functions in your code like this:

import { clearInterval, clearTimeout, setInterval, setTimeout } from 'worker-timers';

The usage is exactly the same (despite of the error handling and the differentiation between intervals and timeouts) as with the corresponding functions on the global scope.

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

clearInterval(intervalId);

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

clearTimeout(timeoutId);

Error Handling

The native WindowTimers are very forgiving. Calling clearInterval() or clearTimeout() without a value or with an id which doesn't exist will get ignored. In contrast to that worker-timers will throw an error when doing so.

// This will return undefined.
window.clearTimeout('not-a-timeout-id');

// This will throw an error.
clearTimeout('not-a-timeout-id');

Differentiation between Intervals and Timeouts

Another difference between worker-timers and WindowTimers is that this package maintains two separate lists to store the ids of intervals and timeouts internally. WindowTimers do only have one list which allows intervals to be cancelled by calling clearTimeout() and the other way round. This is not possible with worker-timers. As mentioned above worker-timers will throw an error when provided with an unknown id.

const periodicWork = () => {};

// This will stop the interval.
const windowId = window.setInterval(periodicWork, 100);
window.clearTimeout(windowId);

// This will throw an error.
const workerId = setInterval(periodicWork, 100);
clearTimeout(workerId);

Server-Side Rendering

This package is intended to be used in the browser and requires the browser to have support for Web Workers. It does not contain any fallback which would allow it to run in another environment like Node.js which doesn't know about Web Workers. This is to prevent this package from silently failing in an unsupported browser. But it also means that it needs to be replaced when used in a web project which also supports server-side rendering. The replacement should be straightforward, at least in theory, because each function has the exact same signature as its corresponding builtin function. But the configuration of a real-life project can be tricky. For a concrete example, please have a look at the worker-timers-ssr-example provided by @newyork-anthonyng. It shows the usage inside of a server-side rendered React app.

Angular (& Zone.js)

If worker-timers is used inside of an Angular app and Zone.js (which is the default) is used to detect changes, the behavior of worker-timers can be confusing. Angular is using Zone.js which is patching the native setInterval() and setTimeout() functions to get notified about the invocation of their callback functions. But Angular (more specifically Zone.js) is not aware of worker-timers and doesn't get notified about any callback invocations. Therefore Angular needs to be notified manually about state changes that occur inside of a callback function which was scheduled with the help of worker-timers.

More Repositories

1

standardized-audio-context

A cross-browser wrapper for the Web Audio API which aims to closely follow the standard.
JavaScript
662
star
2

web-audio-beat-detector

A beat detection utility which is using the Web Audio API.
JavaScript
559
star
3

extendable-media-recorder

An extendable drop-in replacement for the native MediaRecorder.
JavaScript
253
star
4

angular-prerender

A command line tool to prerender Angular Apps.
JavaScript
125
star
5

midi-json-parser

This module is parsing midi files into a human-readable JSON object.
JavaScript
111
star
6

subscribable-things

A collection of reactive wrappers for various browser APIs.
JavaScript
42
star
7

json-midi-encoder

This module encodes a JSON representation of MIDI data into a binary MIDI file.
JavaScript
40
star
8

timing-object

An implementation of the timing object specification.
JavaScript
37
star
9

extendable-media-recorder-wav-encoder

A Wave file encoder for the extendable-media-recorder package.
JavaScript
36
star
10

timingsrc

A library to synchronize a MediaElement with a TimingObject.
JavaScript
31
star
11

timing-provider

An implementation of the timing provider specification.
JavaScript
30
star
12

midi-player

A MIDI player which sends MIDI messages to connected devices.
JavaScript
27
star
13

rxjs-broker

An RxJS message broker for WebRTC DataChannels and WebSockets.
JavaScript
24
star
14

dynamo-converters

A collection of converter functions to get good old JavaScript key/value objects into a DynamoDB friendly schema and back again.
JavaScript
24
star
15

recorder-audio-worklet

This module provides a loader for the RecorderAudioWorkletProcessor and the corresponding RecorderAudioWorkletNode.
JavaScript
24
star
16

angular-audio-context

An Angular wrapper for the Web Audio API's AudioContext.
JavaScript
21
star
17

standardized-audio-context-mock

A mocked version of the standardized-audio-context module.
JavaScript
20
star
18

limiter-audio-worklet

This module provides a loader for the LimiterAudioWorkletProcessor and the corresponding LimiterAudioWorkletNode.
JavaScript
17
star
19

audio-context-timers

A replacement for setInterval() and setTimeout() which works in unfocused windows.
JavaScript
15
star
20

timing-provider-server

A command line tool to spin up a server which can be used with the timing-provider.
JavaScript
15
star
21

video-synchronization-demo

A website to demo usage of the media-sync package with a TimingObject and a TimingProvider.
JavaScript
13
star
22

dynamo-db-local

A wrapper around Amazon's DynamoDB Local to start and stop it from Node.js.
JavaScript
13
star
23

automation-events

A module which provides an implementation of an automation event list.
JavaScript
12
star
24

audio-fingerprinting-file-reader

A reader for files created by audfprint.
JavaScript
11
star
25

web-audio-beat-detector-worker

The worker which is used by the web-audio-beat-detector package.
JavaScript
8
star
26

midi-file-slicer

This module is slicing a midi representation into parts.
JavaScript
7
star
27

web-codecs

A (not yet) extendable and (not yet) complete drop-in replacement for the native WebCodecs API.
JavaScript
7
star
28

limiter-audio-worklet-processor

The AudioWorkletProcessor which is used by the limiter-audio-worklet package.
JavaScript
7
star
29

recorder-audio-worklet-processor

The AudioWorkletProcessor which is used by the recorder-audio-worklet package.
JavaScript
6
star
30

metadata-detector

A tool to locate and strip metadata from files.
JavaScript
6
star
31

midi-json-parser-worker

The worker which is used by the midi-json-parser package.
TypeScript
6
star
32

karma-virtualbox-ie11-launcher

!!! DEPRECATED !!! A Karma launcher for Internet Explorer 11 on VirtualBox.
JavaScript
6
star
33

web-audio-beat-detector-broker

The broker which is used by the web-audio-beat-detector package.
JavaScript
5
star
34

worker-timers-broker

The broker which is used by the worker-timers package.
JavaScript
4
star
35

metadata-detector-streams

A tool to locate and strip metadata from files.
TypeScript
4
star
36

karma-virtualbox-edge-launcher

!!! DEPRECATED !!! A Karma launcher for Edge on VirtualBox.
JavaScript
4
star
37

standardized-audio-context-demo

A demo page to show how to use standardized-audio-context.
JavaScript
4
star
38

timed-audio-buffer-source-node-audio-worklet

This module provides a loader for the TimedAudioBufferSourceNodeAudioWorkletProcessor and the corresponding TimedAudioBufferSourceNodeAudioWorkletNode.
JavaScript
3
star
39

multi-buffer-data-view

A wrapper around the native DataView which can handle multiple ArrayBuffers.
JavaScript
3
star
40

demuxed-2022

My talk at Demuxed 2022.
HTML
3
star
41

worker-timers-worker

The worker which is used by the worker-timers package.
JavaScript
3
star
42

analog4all-client

This is the client for analog4all.
TypeScript
2
star
43

extendable-media-recorder-wav-encoder-worker

The worker which is used by the extendable-media-recorder-wav-encoder package.
JavaScript
2
star
44

web-timing-demo

A website to demo the Web Timing Object.
JavaScript
2
star
45

web-audio-conference-2017

My talk at the Web Audio Conference 2017.
TypeScript
2
star
46

media-encoder-host

This is a module to load and manage media encoders.
JavaScript
2
star
47

fast-unique-numbers

A module to create a set of unique numbers as fast as possible.
JavaScript
2
star
48

json-midi-message-encoder

This module encodes a JSON representation of a MIDI event into a binary MIDI event.
TypeScript
2
star
49

tonejs-synchronization-demo

A website to demo how to connect Tone.js to a Timing Object.
JavaScript
2
star
50

audio-developer-conference-2022

My talk at the Audio Developer Conference in 2022.
TypeScript
2
star
51

broker-factory

A little factory function to create a broker for a JSON-RPC based Web Worker.
JavaScript
2
star
52

analog4all-provider

This is the provider for analog4all.
TypeScript
2
star
53

web-audio-metronome-demo

A website to demo a Web Audio metronome connected to a Web Timing Object.
JavaScript
2
star
54

user-media-audio-visualizer

A super basic visualizer of user media's audio input.
JavaScript
2
star
55

here-maps-type-guards

A guarded version of the TypeScript type definitions for HERE Maps.
TypeScript
2
star
56

create-s3-object-write-stream

Creates a writable stream which uses Amazon's Multipart Upload API under the hood.
JavaScript
2
star
57

rxjs-connector

A module to accept WebRTC DataChannel connections by using WebSockets.
TypeScript
2
star
58

tpac-2022

My talk at the TPAC 2022.
TypeScript
1
star
59

karma-yakbak-preprocessor

!!! DEPRECATED !!! A Karma preprocessor for yakbak.
JavaScript
1
star
60

dynamo-db-provisioner

A lightweight and promise-based wrapper of the AWS SDK to create and delete tables.
JavaScript
1
star
61

worker-factory

A little factory function to create a JSON-RPC based Web Worker implementation.
JavaScript
1
star
62

synchsafe

A module to decode and encode synchsafe integers.
JavaScript
1
star
63

web-audio-meetup-march-2017

My talk at the Web Audio meetup in March 2017.
TypeScript
1
star
64

timed-audio-buffer-source-node-audio-worklet-processor

The AudioWorkletProcessor which is used by the timed-audio-buffer-source-node-audio-worklet package.
JavaScript
1
star
65

tsconfig-holy-grail

This is my personal collection of tsconfig files.
JavaScript
1
star
66

mse-tests

A collection of MSE tests.
JavaScript
1
star
67

web-audio-meetup-may-2019

My talk at the Web Audio meetup in May 2019.
TypeScript
1
star
68

metadata-detector-broker

The broker which is used by the metadata-detector package.
JavaScript
1
star
69

angular-consistent-contenteditable

AngularJS directive to overcome browser inconsisteny when using line breaks in contenteditable.
JavaScript
1
star
70

extendable-media-recorder-wav-encoder-broker

The broker which is used by the extendable-media-recorder-wav-encoder package.
JavaScript
1
star