@oscarpalmer/timer 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,8 +8,6 @@ A better solution for timeout- and interval-based timers.
8
8
 
9
9
  Timer is available on _npm_ as [`@oscarpalmer/timer`](https://www.npmjs.com/package/@oscarpalmer/timer) to be bundled with your awesome projects.
10
10
 
11
- If you don't need to bundle things, you can use the CDN-version and include a script in your proejcts right away, thanks to [jsDelivr](https://www.jsdelivr.com/package/npm/@oscarpalmer/timer) and [UNPKG](https://unpkg.com/@oscarpalmer/timer).
12
-
13
11
  ## Getting started
14
12
 
15
13
  This is fairly lightweight package, so hopefully you'll be up and running in seconds :blush:
@@ -21,65 +19,62 @@ The timers can be called with nice helper methods, which also auto-starts the ti
21
19
  ```typescript
22
20
  import {repeat, wait} from '@oscarpalmer/timer';
23
21
 
24
- let waited = wait(callback, time);
25
- let repeated = repeat(callback, time, count);
22
+ const waited = wait(waitedCallback);
23
+ const repeated = repeat(repeatedCallback, 10);
26
24
  ```
27
25
 
28
- Or they can be created using class syntax, but without being auto-started:
26
+ Or they can be created using the `new`-keyword, but without being auto-started:
29
27
 
30
28
  ```typescript
31
- import {Repeated, Waited} from '@oscarpalmer/timer';
29
+ import {Timer} from '@oscarpalmer/timer';
32
30
 
33
- waited = new Waited(callback, time);
34
- repeated = new Repeated(callback, time, count);
31
+ const waited = new Timer(waitedCallback);
32
+ const repeated = new Timer(repeatedCallback, 10);
35
33
  ```
36
34
 
37
- ### CDN & IIFE
38
-
39
- If you're using Timer by including the file suffixed with `.iife.js` – or one of the CDN-versions mentioned above – you won't have to import any of the classes or methods.
35
+ ## Parameters
40
36
 
41
- Instead, just include a `script`-tag in your HTML linking to Timer and you can access Timer in other scripts, as below:
37
+ When creating a _Timer_, either with the new `new`-keyword or using the functions, you can configure the timer with a few parameters:
42
38
 
43
- ```javascript
44
- // With auto-start
45
- var waited = Timer.wait(callback, time);
46
- var repeated = Timer.repeat(callback, time, count);
47
-
48
- // With manual start
49
- waited = new Timer.Waited(callback, time);
50
- repeated = new Timer.Repeated(callback, time, count);
51
- ```
39
+ |Parameter|Description|
40
+ |--------:|:----------|
41
+ |`callback`|Callback function to be invoked for each run that are __required__ for all timers.<br>For more information on callbacks, please read [the callbacks section](#callbacks).|
42
+ |`count`|How many times the timer should run.<br>If no value is provided, it will default to `1` when using the `new`-keyword and the `wait`-method, but throws an error for the `repeat`-method.|
43
+ |`time`|How many milliseconds between each invokations of the provided callback.<br>Defaults to `0`, which is not really _0_ milliseconds, but close enough :wink:|
44
+ |`after`|A callback to run after the timer finishes, both when cancelled and completed.<br>If _count_ is greater than `1` and _after_ __is not__ `undefined`, a function is expected.|
52
45
 
53
- ## Methods
46
+ ## Methods and properties
54
47
 
55
- Both the nice helper methods and the class syntax create similar objects – `Waited` and `Repeated` – which share methods:
48
+ An instance of _Timer_ also has a few helpful methods and properties:
56
49
 
57
- |Method|Description|
58
- |-----:|:----------|
59
- |`start()`|Starts the timer: necessary when creating a timer using the class syntax _(e.g. `new Waited...`)_, but helpful when the timer needs to be started at other times, as well|
60
- |`stop()`|Stops the timer|
61
- |`restart()`|Restarts the timer|
50
+ |Name|Type|Description|
51
+ |---:|----|:----------|
52
+ |`active`|_Property_|A `boolean` value to check if the timer is running|
53
+ |`finished`|_Property_|A `boolean` value to check if the timer was able to finish|
54
+ |`start()`|_Method_|Starts the timer.<br>Necessary when creating a timer using the class syntax _(e.g. `new Waited...`)_, but helpful when the timer needs to be started at other times, as well.|
55
+ |`stop()`|_Method_|Stops the timer|
56
+ |`restart()`|_Method_|Restarts the timer|
62
57
 
63
58
  ## Callbacks
64
59
 
65
- Callbacks for waited timers do not receive any arguments, but callbacks for repeated ones do:
60
+ Callbacks for both waited and repeated timers receive one parameter:
66
61
 
67
62
  ```typescript
68
- repeat(index => {
63
+ function callback(index) {
69
64
  // 'index' is the current step
70
65
  // starts at 0, goes up to a maximum of count - 1
71
66
  // for this example: 0 → 9
72
- }, 0, 10);
67
+ };
73
68
  ```
74
69
 
75
- When you create a repeated timer, you can also provide a fourth parameter to act as a callback to run when the timer stops, as below:
70
+ When you create a repeated timer, you can also provide a callback to run when the timer stops, as below:
76
71
 
77
72
  ```typescript
78
73
  function after(finished: boolean) {
79
74
  // Let's do something fun!
80
75
  }
81
76
 
82
- repeat(() => {}, 0, 10, after);
77
+ repeat(() => {}, 10, after);
83
78
  ```
84
79
 
85
80
  The `finished`-parameter for the `after`-function can be used to determine if the timer was stopped manually, or if it was able to finish its work.
package/dist/timer.js CHANGED
@@ -1,162 +1,111 @@
1
- /**
2
- * @callback AfterCallback
3
- * @param {boolean} finished Did the timer finish?
4
- * @returns {void}
5
- */
6
- /**
7
- * @callback RepeatedCallback
8
- * @param {number} index The index of the current iteration
9
- * @returns {void}
10
- */
11
- const callbacks = new WeakMap();
12
- const configuration = new WeakMap();
13
- const state = new WeakMap();
14
- const milliseconds = Math.round(1000 / 60);
15
- function run(timed) {
16
- const timedConfiguration = configuration.get(timed);
17
- const timedCallbacks = callbacks.get(timed);
18
- const timedState = state.get(timed);
19
- timedState.active = true;
20
- timedState.finished = false;
21
- const isRepeated = timed instanceof Repeated;
22
- let index = 0;
23
- let start;
24
- function step(timestamp) {
25
- if (!timedState.active) {
26
- return;
27
- }
28
- start ?? (start = timestamp);
29
- const elapsed = timestamp - start;
30
- const elapsedMinimum = elapsed - milliseconds;
31
- const elapsedMaximum = elapsed + milliseconds;
32
- if (
33
- elapsedMinimum < timedConfiguration.time &&
34
- timedConfiguration.time < elapsedMaximum
35
- ) {
36
- if (timedState.active) {
37
- timedCallbacks.default(isRepeated ? index : undefined);
38
- }
39
- index += 1;
40
- if (isRepeated && index < timedConfiguration.count) {
41
- start = undefined;
42
- } else {
43
- timedState.finished = true;
44
- timed.stop();
45
- return;
46
- }
47
- }
48
- timedState.frame = globalThis.requestAnimationFrame(step);
49
- }
50
- timedState.frame = globalThis.requestAnimationFrame(step);
1
+ // src/index.ts
2
+ var run = function(timer) {
3
+ const { _configuration, _state } = timer;
4
+ _state.active = true;
5
+ _state.finished = false;
6
+ const isRepeated = _configuration.count > 1;
7
+ let index = 0;
8
+ let start;
9
+ function step(timestamp) {
10
+ if (!_state.active) {
11
+ return;
12
+ }
13
+ start ??= timestamp;
14
+ const elapsed = timestamp - start;
15
+ const elapsedMinimum = elapsed - milliseconds;
16
+ const elapsedMaximum = elapsed + milliseconds;
17
+ if (elapsedMinimum < _configuration.time && _configuration.time < elapsedMaximum) {
18
+ if (_state.active) {
19
+ _configuration.callbacks.default(index);
20
+ }
21
+ index += 1;
22
+ if (isRepeated && index < _configuration.count) {
23
+ start = undefined;
24
+ } else {
25
+ _state.finished = true;
26
+ timer.stop();
27
+ return;
28
+ }
29
+ }
30
+ _state.frame = requestAnimationFrame(step);
31
+ }
32
+ _state.frame = requestAnimationFrame(step);
33
+ };
34
+ function repeat(callback, count, afterOrTime, after) {
35
+ if (typeof count !== "number" || count < 2) {
36
+ throw new TypeError("A repeated timer must have a number greater than or equal to 2 as its run count");
37
+ }
38
+ const afterOrTimeIsFunction = typeof afterOrTime === "function";
39
+ return new Timer(callback, afterOrTimeIsFunction ? 0 : afterOrTime, count, afterOrTimeIsFunction ? afterOrTime : after).start();
51
40
  }
52
- class Timed {
53
- get active() {
54
- return state.get(this)?.active ?? false;
55
- }
56
- get finished() {
57
- return !this.active && (state.get(this)?.finished ?? false);
58
- }
59
- /**
60
- * @param {Callback} callback
61
- * @param {number} time
62
- * @param {number} count
63
- * @param {AfterCallback=} afterCallback
64
- */
65
- constructor(callback, time, count, afterCallback) {
66
- const isRepeated = this instanceof Repeated;
67
- const type = isRepeated ? 'repeated' : 'waited';
68
- if (typeof callback !== 'function') {
69
- throw new TypeError(`A ${type} timer must have a callback function`);
70
- }
71
- if (typeof time !== 'number' || time < 0) {
72
- throw new TypeError(
73
- `A ${type} timer must have a non-negative number as its time`,
74
- );
75
- }
76
- if (isRepeated && (typeof count !== 'number' || count < 2)) {
77
- throw new TypeError(
78
- 'A repeated timer must have a number above 1 as its repeat count',
79
- );
80
- }
81
- if (
82
- isRepeated &&
83
- afterCallback !== undefined &&
84
- typeof afterCallback !== 'function'
85
- ) {
86
- throw new TypeError(
87
- "A repeated timer's after-callback must be a function",
88
- );
89
- }
90
- callbacks.set(this, {
91
- after: afterCallback,
92
- default: callback,
93
- });
94
- configuration.set(this, {count, time});
95
- state.set(this, {
96
- active: false,
97
- finished: false,
98
- });
99
- }
100
- restart() {
101
- this.stop();
102
- run(this);
103
- return this;
104
- }
105
- start() {
106
- if (!this.active) {
107
- run(this);
108
- }
109
- return this;
110
- }
111
- stop() {
112
- const timedCallbacks = callbacks.get(this);
113
- const timedState = state.get(this);
114
- timedState.active = false;
115
- if (timedState.frame === undefined) {
116
- return this;
117
- }
118
- globalThis.cancelAnimationFrame(timedState.frame);
119
- timedCallbacks.after?.(this.finished);
120
- timedState.frame = undefined;
121
- return this;
122
- }
123
- }
124
- /**
125
- * A timer that waits and runs repeatedly
126
- */
127
- class Repeated extends Timed {}
128
- /**
129
- * A timer that waits and runs once
130
- */
131
- class Waited extends Timed {
132
- /**
133
- * Creates a new waited timer
134
- * @param {() => void} callback
135
- * @param {number} time
136
- */
137
- constructor(callback, time) {
138
- super(callback, time, 1);
139
- }
140
- }
141
- /**
142
- * Creates and starts a new repeated timer
143
- * @param {RepeatedCallback} callback
144
- * @param {number} time
145
- * @param {number} count
146
- * @param {AfterCallback=} afterCallback
147
- * @return {Repeated}
148
- */
149
- function repeat(callback, time, count, afterCallback) {
150
- return new Repeated(callback, time, count, afterCallback).start();
151
- }
152
- /**
153
- * Creates and starts a new waited timer
154
- * @param {() => void} callback
155
- * @param {number} time
156
- * @return {Waited}
157
- */
158
41
  function wait(callback, time) {
159
- return new Waited(callback, time).start();
42
+ return new Timer(callback, time).start();
160
43
  }
44
+ var milliseconds = Math.round(16.666666666666668);
161
45
 
162
- export {Repeated, Waited, repeat, wait};
46
+ class Timer {
47
+ get active() {
48
+ return this._state.active;
49
+ }
50
+ get finished() {
51
+ return this._state.finished;
52
+ }
53
+ constructor(callback, time, count, afterCallback) {
54
+ if (typeof callback !== "function") {
55
+ throw new TypeError("A timer must have a callback function");
56
+ }
57
+ const actualTime = typeof time === "number" ? time : 0;
58
+ if (actualTime < 0) {
59
+ throw new TypeError("A timer must have a non-negative number as its time");
60
+ }
61
+ const actualCount = typeof count === "number" ? count : 1;
62
+ if (actualCount < 1) {
63
+ throw new TypeError("A timer must have a number greater than or equal to 1 as its run count");
64
+ }
65
+ if (actualCount > 1 && afterCallback !== undefined && typeof afterCallback !== "function") {
66
+ throw new TypeError("A repeated timer's after-callback must be a function");
67
+ }
68
+ Object.defineProperty(this, "_configuration", {
69
+ value: {
70
+ callbacks: {
71
+ after: afterCallback,
72
+ default: callback
73
+ },
74
+ count: actualCount,
75
+ time: actualTime
76
+ }
77
+ });
78
+ Object.defineProperty(this, "_state", {
79
+ value: {
80
+ active: false,
81
+ finished: false
82
+ }
83
+ });
84
+ }
85
+ restart() {
86
+ this.stop();
87
+ run(this);
88
+ return this;
89
+ }
90
+ start() {
91
+ if (!this._state.active) {
92
+ run(this);
93
+ }
94
+ return this;
95
+ }
96
+ stop() {
97
+ this._state.active = false;
98
+ if (this._state.frame === undefined) {
99
+ return this;
100
+ }
101
+ cancelAnimationFrame(this._state.frame);
102
+ this._configuration.callbacks.after?.(this._state.finished);
103
+ this._state.frame = undefined;
104
+ return this;
105
+ }
106
+ }
107
+ export {
108
+ wait,
109
+ repeat,
110
+ Timer
111
+ };
package/package.json CHANGED
@@ -3,31 +3,17 @@
3
3
  "name": "Oscar Palmér",
4
4
  "url": "https://oscarpalmer.se"
5
5
  },
6
- "browser": "dist/timer.iife.js",
7
6
  "description": "A better solution for timeout- and interval-based timers.",
8
7
  "devDependencies": {
9
- "@happy-dom/global-registrator": "^11.0",
10
- "@rollup/plugin-typescript": "^11.1",
8
+ "@biomejs/biome": "^1.4",
9
+ "@happy-dom/global-registrator": "^12.10",
11
10
  "bun": "^1.0",
12
- "prettier": "^3.0",
13
- "rollup": "^3.29",
14
- "typescript": "^5.2",
15
- "xo": "^0.56"
11
+ "typescript": "^5.3"
16
12
  },
17
- "files": [
18
- "dist",
19
- "src",
20
- "types"
21
- ],
22
- "jsdelivr": "dist/timer.iife.js",
23
- "keywords": [
24
- "timer",
25
- "setTimeout",
26
- "setInterval",
27
- "requestAnimationFrame"
28
- ],
13
+ "files": ["dist", "src", "types"],
14
+ "keywords": ["timer", "setTimeout", "setInterval", "requestAnimationFrame"],
29
15
  "license": "MIT",
30
- "main": "dist/timer.iife.js",
16
+ "main": "dist/timer.js",
31
17
  "module": "dist/timer.js",
32
18
  "name": "@oscarpalmer/timer",
33
19
  "prettier": {
@@ -43,26 +29,13 @@
43
29
  "url": "git+https://github.com/oscarpalmer/timer.git"
44
30
  },
45
31
  "scripts": {
46
- "build": "npm run build:esm && npm run build:iife",
47
- "build:esm": "rollup -c",
48
- "build:iife": "rollup -c --environment ROLLUP_FORMAT:iife",
32
+ "build": "bun build ./src/index.ts --outfile ./dist/timer.js",
49
33
  "test": "bun test --coverage",
50
- "types": "tsc ./src/index.ts --outdir ./types --declaration --emitDeclarationOnly",
34
+ "types": "bunx tsc -p ./tsconfig.json",
51
35
  "watch": "rollup -c -w",
52
36
  "xo": "xo ./src/*.ts --env browser"
53
37
  },
54
38
  "type": "module",
55
39
  "types": "src/index.d.ts",
56
- "unpkg": "dist/timer.iife.js",
57
- "version": "0.19.0",
58
- "xo": {
59
- "envs": [
60
- "browser"
61
- ],
62
- "prettier": true,
63
- "rules": {
64
- "import/extensions": "off",
65
- "import/no-cycle": "off"
66
- }
67
- }
68
- }
40
+ "version": "0.20.0"
41
+ }
package/src/index.ts CHANGED
@@ -1,22 +1,17 @@
1
+ export type AfterCallback = (finished: boolean) => void;
2
+
1
3
  type Callbacks = {
2
4
  after: AfterCallback | undefined;
3
- default: (index?: number) => void;
5
+ default: IndexedCallback;
4
6
  };
5
7
 
6
8
  type Configuration = {
9
+ callbacks: Callbacks;
7
10
  count: number;
8
11
  time: number;
9
12
  };
10
13
 
11
- /**
12
- * @param {boolean} finished Did the timer finish?
13
- */
14
- export type AfterCallback = (finished: boolean) => void;
15
-
16
- /**
17
- * @param {number} index The index of the current iteration
18
- */
19
- export type RepeatedCallback = (index: number) => void;
14
+ type IndexedCallback = (index: number) => void;
20
15
 
21
16
  type State = {
22
17
  active: boolean;
@@ -24,28 +19,23 @@ type State = {
24
19
  frame?: number;
25
20
  };
26
21
 
27
- const callbacks = new WeakMap<Timed<never, never>, Callbacks>();
28
- const configuration = new WeakMap<Timed<never, never>, Configuration>();
29
- const state = new WeakMap<Timed<never, never>, State>();
30
-
31
22
  const milliseconds = Math.round(1000 / 60);
32
23
 
33
- function run(timed: Timed<never, never>): void {
34
- const timedConfiguration = configuration.get(timed)!;
35
- const timedCallbacks = callbacks.get(timed)!;
36
- const timedState = state.get(timed)!;
24
+ function run(timer: Timer): void {
25
+ // @ts-expect-error Keep private status, but allow access
26
+ const {_configuration, _state} = timer;
37
27
 
38
- timedState.active = true;
39
- timedState.finished = false;
28
+ _state.active = true;
29
+ _state.finished = false;
40
30
 
41
- const isRepeated = timed instanceof Repeated;
31
+ const isRepeated = _configuration.count > 1;
42
32
 
43
33
  let index = 0;
44
34
 
45
35
  let start;
46
36
 
47
37
  function step(timestamp: DOMHighResTimeStamp): void {
48
- if (!timedState.active) {
38
+ if (!_state.active) {
49
39
  return;
50
40
  }
51
41
 
@@ -57,39 +47,42 @@ function run(timed: Timed<never, never>): void {
57
47
  const elapsedMaximum = elapsed + milliseconds;
58
48
 
59
49
  if (
60
- elapsedMinimum < timedConfiguration.time &&
61
- timedConfiguration.time < elapsedMaximum
50
+ elapsedMinimum < _configuration.time &&
51
+ _configuration.time < elapsedMaximum
62
52
  ) {
63
- if (timedState.active) {
64
- timedCallbacks.default(isRepeated ? index : undefined);
53
+ if (_state.active) {
54
+ _configuration.callbacks.default(index);
65
55
  }
66
56
 
67
57
  index += 1;
68
58
 
69
- if (isRepeated && index < timedConfiguration.count) {
59
+ if (isRepeated && index < _configuration.count) {
70
60
  start = undefined;
71
61
  } else {
72
- timedState.finished = true;
62
+ _state.finished = true;
73
63
 
74
- timed.stop();
64
+ timer.stop();
75
65
 
76
66
  return;
77
67
  }
78
68
  }
79
69
 
80
- timedState.frame = globalThis.requestAnimationFrame(step);
70
+ _state.frame = requestAnimationFrame(step);
81
71
  }
82
72
 
83
- timedState.frame = globalThis.requestAnimationFrame(step);
73
+ _state.frame = requestAnimationFrame(step);
84
74
  }
85
75
 
86
- class Timed<Type, Callback> {
76
+ export class Timer {
77
+ private declare readonly _configuration: Configuration;
78
+ private declare readonly _state: State;
79
+
87
80
  get active(): boolean {
88
- return state.get(this as never)?.active ?? false;
81
+ return this._state.active;
89
82
  }
90
83
 
91
84
  get finished(): boolean {
92
- return !this.active && (state.get(this as never)?.finished ?? false);
85
+ return this._state.finished;
93
86
  }
94
87
 
95
88
  /**
@@ -99,33 +92,33 @@ class Timed<Type, Callback> {
99
92
  * @param {AfterCallback=} afterCallback
100
93
  */
101
94
  constructor(
102
- callback: Callback,
103
- time: number,
104
- count: number,
95
+ callback: IndexedCallback,
96
+ time?: number,
97
+ count?: number,
105
98
  afterCallback?: AfterCallback,
106
99
  ) {
107
- const isRepeated = this instanceof Repeated;
108
-
109
- const type = isRepeated ? 'repeated' : 'waited';
110
-
111
100
  if (typeof callback !== 'function') {
112
- throw new TypeError(`A ${type} timer must have a callback function`);
101
+ throw new TypeError('A timer must have a callback function');
113
102
  }
114
103
 
115
- if (typeof time !== 'number' || time < 0) {
104
+ const actualTime = typeof time === 'number' ? time : 0;
105
+
106
+ if (actualTime < 0) {
116
107
  throw new TypeError(
117
- `A ${type} timer must have a non-negative number as its time`,
108
+ 'A timer must have a non-negative number as its time',
118
109
  );
119
110
  }
120
111
 
121
- if (isRepeated && (typeof count !== 'number' || count < 2)) {
112
+ const actualCount = typeof count === 'number' ? count : 1;
113
+
114
+ if (actualCount < 1) {
122
115
  throw new TypeError(
123
- 'A repeated timer must have a number above 1 as its repeat count',
116
+ 'A timer must have a number greater than or equal to 1 as its run count',
124
117
  );
125
118
  }
126
119
 
127
120
  if (
128
- isRepeated &&
121
+ actualCount > 1 &&
129
122
  afterCallback !== undefined &&
130
123
  typeof afterCallback !== 'function'
131
124
  ) {
@@ -134,97 +127,103 @@ class Timed<Type, Callback> {
134
127
  );
135
128
  }
136
129
 
137
- callbacks.set(this as never, {
138
- after: afterCallback,
139
- default: callback as never,
130
+ Object.defineProperty(this, '_configuration', {
131
+ value: {
132
+ callbacks: {
133
+ after: afterCallback,
134
+ default: callback,
135
+ },
136
+ count: actualCount,
137
+ time: actualTime,
138
+ },
140
139
  });
141
140
 
142
- configuration.set(this as never, {count, time});
143
-
144
- state.set(this as never, {
145
- active: false,
146
- finished: false,
141
+ Object.defineProperty(this, '_state', {
142
+ value: {
143
+ active: false,
144
+ finished: false,
145
+ },
147
146
  });
148
147
  }
149
148
 
150
- restart(): Type {
149
+ restart(): Timer {
151
150
  this.stop();
152
151
 
153
- run(this as never);
152
+ run(this);
154
153
 
155
- return this as never;
154
+ return this;
156
155
  }
157
156
 
158
- start(): Type {
159
- if (!this.active) {
160
- run(this as never);
157
+ start(): Timer {
158
+ if (!this._state.active) {
159
+ run(this);
161
160
  }
162
161
 
163
- return this as never;
162
+ return this;
164
163
  }
165
164
 
166
- stop(): Type {
167
- const timedCallbacks = callbacks.get(this as never)!;
168
- const timedState = state.get(this as never)!;
165
+ stop(): Timer {
166
+ this._state.active = false;
169
167
 
170
- timedState.active = false;
171
-
172
- if (timedState.frame === undefined) {
173
- return this as never;
168
+ if (this._state.frame === undefined) {
169
+ return this;
174
170
  }
175
171
 
176
- globalThis.cancelAnimationFrame(timedState.frame);
172
+ cancelAnimationFrame(this._state.frame);
177
173
 
178
- timedCallbacks.after?.(this.finished);
174
+ this._configuration.callbacks.after?.(this._state.finished);
179
175
 
180
- timedState.frame = undefined;
176
+ this._state.frame = undefined;
181
177
 
182
- return this as never;
183
- }
184
- }
185
-
186
- /**
187
- * A timer that waits and runs repeatedly
188
- */
189
- export class Repeated extends Timed<Repeated, RepeatedCallback> {}
190
-
191
- /**
192
- * A timer that waits and runs once
193
- */
194
- export class Waited extends Timed<Waited, () => void> {
195
- /**
196
- * Creates a new waited timer
197
- * @param {() => void} callback
198
- * @param {number} time
199
- */
200
- constructor(callback: () => void, time: number) {
201
- super(callback, time, 1);
178
+ return this;
202
179
  }
203
180
  }
204
181
 
205
182
  /**
206
183
  * Creates and starts a new repeated timer
207
- * @param {RepeatedCallback} callback
208
- * @param {number} time
209
- * @param {number} count
210
- * @param {AfterCallback=} afterCallback
211
- * @return {Repeated}
212
184
  */
185
+ export function repeat(callback: IndexedCallback, count: number): Timer;
186
+ export function repeat(
187
+ callback: IndexedCallback,
188
+ count: number,
189
+ afterCallback: AfterCallback,
190
+ ): Timer;
213
191
  export function repeat(
214
- callback: RepeatedCallback,
192
+ callback: IndexedCallback,
193
+ count: number,
215
194
  time: number,
195
+ ): Timer;
196
+ export function repeat(
197
+ callback: IndexedCallback,
216
198
  count: number,
217
- afterCallback?: AfterCallback,
218
- ): Repeated {
219
- return new Repeated(callback as never, time, count, afterCallback).start();
199
+ time: number,
200
+ afterCallback: AfterCallback,
201
+ ): Timer;
202
+ export function repeat(
203
+ callback: IndexedCallback,
204
+ count: number,
205
+ afterOrTime?: number | AfterCallback,
206
+ after?: AfterCallback,
207
+ ): Timer {
208
+ if (typeof count !== 'number' || count < 2) {
209
+ throw new TypeError(
210
+ 'A repeated timer must have a number greater than or equal to 2 as its run count',
211
+ );
212
+ }
213
+
214
+ const afterOrTimeIsFunction = typeof afterOrTime === 'function';
215
+
216
+ return new Timer(
217
+ callback,
218
+ afterOrTimeIsFunction ? 0 : afterOrTime,
219
+ count,
220
+ afterOrTimeIsFunction ? afterOrTime : after,
221
+ ).start();
220
222
  }
221
223
 
222
224
  /**
223
225
  * Creates and starts a new waited timer
224
- * @param {() => void} callback
225
- * @param {number} time
226
- * @return {Waited}
227
226
  */
228
- export function wait(callback: () => void, time: number): Waited {
229
- return new Waited(callback, time).start();
227
+ export function wait(callback: IndexedCallback, time?: number): Timer {
228
+ return new Timer(callback, time).start();
230
229
  }
package/types/index.d.ts CHANGED
@@ -1,72 +1,30 @@
1
- /**
2
- * @param {boolean} finished Did the timer finish?
3
- */
4
1
  export type AfterCallback = (finished: boolean) => void;
5
-
6
- /**
7
- * @param {number} index The index of the current iteration
8
- */
9
- export type RepeatedCallback = (index: number) => void;
10
-
11
- declare class Timed<Type, Callback> {
12
- get active(): boolean;
13
- get finished(): boolean;
14
-
15
- /**
16
- * @param {Callback} callback
17
- * @param {number} time
18
- * @param {number} count
19
- * @param {AfterCallback=} afterCallback
20
- */
21
-
22
- constructor(
23
- callback: () => void | ((index: number) => void),
24
- time: number,
25
- count: number,
26
- afterCallback?: AfterCallback,
27
- );
28
-
29
- restart(): Type;
30
- start(): Type;
31
- stop(): Type;
32
- }
33
-
34
- /**
35
- * A timer that waits and runs repeatedly
36
- */
37
- export declare class Repeated extends Timed<Repeated, RepeatedCallback> {}
38
-
39
- /**
40
- * A timer that waits and runs once
41
- */
42
- export declare class Waited extends Timed<Waited, () => void> {
43
- /**
44
- * Creates a new waited timer
45
- * @param {() => void} callback
46
- * @param {number} time
47
- */
48
- constructor(callback: () => void, time: number);
2
+ type IndexedCallback = (index: number) => void;
3
+ export declare class Timer {
4
+ private readonly _configuration;
5
+ private readonly _state;
6
+ get active(): boolean;
7
+ get finished(): boolean;
8
+ /**
9
+ * @param {Callback} callback
10
+ * @param {number} time
11
+ * @param {number} count
12
+ * @param {AfterCallback=} afterCallback
13
+ */
14
+ constructor(callback: IndexedCallback, time?: number, count?: number, afterCallback?: AfterCallback);
15
+ restart(): Timer;
16
+ start(): Timer;
17
+ stop(): Timer;
49
18
  }
50
-
51
19
  /**
52
20
  * Creates and starts a new repeated timer
53
- * @param {RepeatedCallback} callback
54
- * @param {number} time
55
- * @param {number} count
56
- * @param {AfterCallback=} afterCallback
57
- * @return {Repeated}
58
21
  */
59
- export declare function repeat(
60
- callback: RepeatedCallback,
61
- time: number,
62
- count: number,
63
- afterCallback?: AfterCallback,
64
- ): Repeated;
65
-
22
+ export declare function repeat(callback: IndexedCallback, count: number): Timer;
23
+ export declare function repeat(callback: IndexedCallback, count: number, afterCallback: AfterCallback): Timer;
24
+ export declare function repeat(callback: IndexedCallback, count: number, time: number): Timer;
25
+ export declare function repeat(callback: IndexedCallback, count: number, time: number, afterCallback: AfterCallback): Timer;
66
26
  /**
67
27
  * Creates and starts a new waited timer
68
- * @param {() => void} callback
69
- * @param {number} time
70
- * @return {Waited}
71
28
  */
72
- export declare function wait(callback: () => void, time: number): Waited;
29
+ export declare function wait(callback: IndexedCallback, time?: number): Timer;
30
+ export {};
@@ -1,162 +0,0 @@
1
- var Timer = (function (exports) {
2
- 'use strict';
3
-
4
- const callbacks = new WeakMap();
5
- const configuration = new WeakMap();
6
- const state = new WeakMap();
7
- const milliseconds = Math.round(1000 / 60);
8
- function run(timed) {
9
- const timedConfiguration = configuration.get(timed);
10
- const timedCallbacks = callbacks.get(timed);
11
- const timedState = state.get(timed);
12
- timedState.active = true;
13
- timedState.finished = false;
14
- const isRepeated = timed instanceof Repeated;
15
- let index = 0;
16
- let start;
17
- function step(timestamp) {
18
- if (!timedState.active) {
19
- return;
20
- }
21
- start ?? (start = timestamp);
22
- const elapsed = timestamp - start;
23
- const elapsedMinimum = elapsed - milliseconds;
24
- const elapsedMaximum = elapsed + milliseconds;
25
- if (
26
- elapsedMinimum < timedConfiguration.time &&
27
- timedConfiguration.time < elapsedMaximum
28
- ) {
29
- if (timedState.active) {
30
- timedCallbacks.default(isRepeated ? index : undefined);
31
- }
32
- index += 1;
33
- if (isRepeated && index < timedConfiguration.count) {
34
- start = undefined;
35
- } else {
36
- timedState.finished = true;
37
- timed.stop();
38
- return;
39
- }
40
- }
41
- timedState.frame = globalThis.requestAnimationFrame(step);
42
- }
43
- timedState.frame = globalThis.requestAnimationFrame(step);
44
- }
45
- class Timed {
46
- get active() {
47
- return state.get(this)?.active ?? false;
48
- }
49
- get finished() {
50
- return !this.active && (state.get(this)?.finished ?? false);
51
- }
52
- /**
53
- * @param {Callback} callback
54
- * @param {number} time
55
- * @param {number} count
56
- * @param {AfterCallback=} afterCallback
57
- */
58
- constructor(callback, time, count, afterCallback) {
59
- const isRepeated = this instanceof Repeated;
60
- const type = isRepeated ? 'repeated' : 'waited';
61
- if (typeof callback !== 'function') {
62
- throw new TypeError(`A ${type} timer must have a callback function`);
63
- }
64
- if (typeof time !== 'number' || time < 0) {
65
- throw new TypeError(
66
- `A ${type} timer must have a non-negative number as its time`,
67
- );
68
- }
69
- if (isRepeated && (typeof count !== 'number' || count < 2)) {
70
- throw new TypeError(
71
- 'A repeated timer must have a number above 1 as its repeat count',
72
- );
73
- }
74
- if (
75
- isRepeated &&
76
- afterCallback !== undefined &&
77
- typeof afterCallback !== 'function'
78
- ) {
79
- throw new TypeError(
80
- "A repeated timer's after-callback must be a function",
81
- );
82
- }
83
- callbacks.set(this, {
84
- after: afterCallback,
85
- default: callback,
86
- });
87
- configuration.set(this, {count, time});
88
- state.set(this, {
89
- active: false,
90
- finished: false,
91
- });
92
- }
93
- restart() {
94
- this.stop();
95
- run(this);
96
- return this;
97
- }
98
- start() {
99
- if (!this.active) {
100
- run(this);
101
- }
102
- return this;
103
- }
104
- stop() {
105
- const timedCallbacks = callbacks.get(this);
106
- const timedState = state.get(this);
107
- timedState.active = false;
108
- if (timedState.frame === undefined) {
109
- return this;
110
- }
111
- globalThis.cancelAnimationFrame(timedState.frame);
112
- timedCallbacks.after?.(this.finished);
113
- timedState.frame = undefined;
114
- return this;
115
- }
116
- }
117
- /**
118
- * A timer that waits and runs repeatedly
119
- */
120
- class Repeated extends Timed {}
121
- /**
122
- * A timer that waits and runs once
123
- */
124
- class Waited extends Timed {
125
- /**
126
- * Creates a new waited timer
127
- * @param {() => void} callback
128
- * @param {number} time
129
- */
130
- constructor(callback, time) {
131
- super(callback, time, 1);
132
- }
133
- }
134
- /**
135
- * Creates and starts a new repeated timer
136
- * @param {RepeatedCallback} callback
137
- * @param {number} time
138
- * @param {number} count
139
- * @param {AfterCallback=} afterCallback
140
- * @return {Repeated}
141
- */
142
- function repeat(callback, time, count, afterCallback) {
143
- return new Repeated(callback, time, count, afterCallback).start();
144
- }
145
- /**
146
- * Creates and starts a new waited timer
147
- * @param {() => void} callback
148
- * @param {number} time
149
- * @return {Waited}
150
- */
151
- function wait(callback, time) {
152
- return new Waited(callback, time).start();
153
- }
154
-
155
- exports.Repeated = Repeated;
156
- exports.Waited = Waited;
157
- exports.repeat = repeat;
158
- exports.wait = wait;
159
-
160
- return exports;
161
-
162
- })({});