@oscarpalmer/timer 0.30.0 → 0.32.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/dist/when.js CHANGED
@@ -1,13 +1,19 @@
1
- import { noop } from './node_modules/@oscarpalmer/atoms/dist/function.js';
1
+ import { noop } from '@oscarpalmer/atoms/function';
2
2
  import { milliseconds, destroyedMessage, startedMessage } from './constants.js';
3
3
  import { getValidNumber } from './get.js';
4
+ import './global.js';
4
5
  import { TimerTrace } from './models.js';
5
6
  import { Timer } from './timer.js';
6
- import { work } from './work.js';
7
7
 
8
8
  class When {
9
9
  $timer = "when";
10
- state;
10
+ state = {
11
+ promise: void 0,
12
+ rejecter: void 0,
13
+ resolver: void 0,
14
+ started: false,
15
+ timer: void 0
16
+ };
11
17
  /**
12
18
  * Is the timer active?
13
19
  */
@@ -32,8 +38,47 @@ class When {
32
38
  get trace() {
33
39
  return globalThis._oscarpalmer_timer_debug ?? false ? this.state.timer?.trace : void 0;
34
40
  }
35
- constructor(state) {
36
- this.state = state;
41
+ constructor(condition, options) {
42
+ const { state } = this;
43
+ state.promise = new Promise((resolve, reject) => {
44
+ state.resolver = resolve;
45
+ state.rejecter = reject;
46
+ });
47
+ let result = false;
48
+ this.state.timer = new Timer(
49
+ "when",
50
+ {
51
+ callback() {
52
+ try {
53
+ if (condition()) {
54
+ result = true;
55
+ state.timer.stop();
56
+ }
57
+ } catch {
58
+ state.timer.stop();
59
+ }
60
+ },
61
+ trace: new TimerTrace().stack
62
+ },
63
+ {
64
+ onAfter: () => {
65
+ if (result) {
66
+ state.resolver?.();
67
+ } else {
68
+ state.rejecter?.();
69
+ }
70
+ this.destroy();
71
+ },
72
+ onError: () => {
73
+ state.rejecter?.();
74
+ this.destroy();
75
+ },
76
+ count: getValidNumber(options?.count),
77
+ interval: getValidNumber(options?.interval, milliseconds),
78
+ timeout: getValidNumber(options?.timeout)
79
+ },
80
+ false
81
+ );
37
82
  }
38
83
  /**
39
84
  * Continues the timer _(if it was paused)_
@@ -46,11 +91,12 @@ class When {
46
91
  * Destroys the timer _(and stops it,if it was running)_
47
92
  */
48
93
  destroy() {
49
- this.state.timer?.destroy();
50
- this.state.promise = void 0;
51
- this.state.resolver = noop;
52
- this.state.rejecter = noop;
53
- this.state.timer = void 0;
94
+ const { state } = this;
95
+ state.timer?.destroy();
96
+ state.promise = void 0;
97
+ state.resolver = noop;
98
+ state.rejecter = noop;
99
+ state.timer = void 0;
54
100
  }
55
101
  /**
56
102
  * Pauses the timer _(if it was running)_
@@ -71,63 +117,20 @@ class When {
71
117
  */
72
118
  // biome-ignore lint/suspicious/noThenProperty: returning a promise-like object, so it's ok ;)
73
119
  then(resolve, reject) {
74
- if (this.state.timer == null || this.state?.started) {
75
- throw new Error(
76
- this.state.timer == null ? destroyedMessage : startedMessage
77
- );
120
+ const { state } = this;
121
+ if (state.timer == null) {
122
+ throw new Error(destroyedMessage);
123
+ }
124
+ if (state.started) {
125
+ throw new Error(startedMessage);
78
126
  }
79
- this.state.started = true;
80
- this.state.timer.start();
81
- return this.state.promise.then(resolve ?? noop, reject ?? noop);
127
+ state.started = true;
128
+ state.timer.start();
129
+ return state.promise.then(resolve ?? noop, reject ?? noop);
82
130
  }
83
131
  }
84
132
  function when(condition, options) {
85
- let called = false;
86
- let result = false;
87
- const state = {
88
- started: false,
89
- timer: new Timer(
90
- "when",
91
- work,
92
- {
93
- callback() {
94
- if (condition()) {
95
- result = true;
96
- state.timer.stop();
97
- }
98
- },
99
- trace: new TimerTrace().stack
100
- },
101
- {
102
- onAfter() {
103
- if (!(state.timer?.paused ?? false) && !called) {
104
- called = true;
105
- if (result) {
106
- state.resolver?.();
107
- } else {
108
- state.rejecter?.();
109
- }
110
- instance.destroy();
111
- }
112
- },
113
- onError() {
114
- state.rejecter?.();
115
- instance.destroy();
116
- },
117
- count: getValidNumber(options?.count),
118
- interval: getValidNumber(options?.interval, milliseconds),
119
- timeout: getValidNumber(options?.timeout)
120
- },
121
- false
122
- )
123
- };
124
- const promise = new Promise((resolve, reject) => {
125
- state.resolver = resolve;
126
- state.rejecter = reject;
127
- });
128
- state.promise = promise;
129
- const instance = new When(state);
130
- return instance;
133
+ return new When(condition, options);
131
134
  }
132
135
 
133
136
  export { when };
package/dist/work.cjs CHANGED
@@ -4,6 +4,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
4
 
5
5
  const constants = require('./constants.cjs');
6
6
 
7
+ function endOrRestart(type, timer, state, options) {
8
+ cancelAnimationFrame(state.frame);
9
+ if (type === "stop") {
10
+ options.onAfter?.(false);
11
+ }
12
+ state.active = false;
13
+ state.frame = void 0;
14
+ state.paused = type === "pause";
15
+ return type === "restart" ? work("start", timer, state, options) : timer.instance;
16
+ }
7
17
  function finish(timer, state, options, success) {
8
18
  constants.activeTimers.delete(timer.instance);
9
19
  state.active = false;
@@ -15,29 +25,12 @@ function finish(timer, state, options, success) {
15
25
  options.onAfter?.(success);
16
26
  }
17
27
  }
18
- function work(type, timer, state, options) {
19
- if (state.destroyed && type !== "stop" || (state.active ? constants.beginTypes.has(type) : constants.endTypes.has(type))) {
20
- return timer.instance;
21
- }
22
- const pausable = constants.pauseTypes.has(type);
23
- state.elapsed = pausable ? state.elapsed : 0;
24
- state.index = pausable ? state.index : 0;
25
- state.total = pausable ? state.total : 0;
26
- if (constants.endOrRestartTypes.has(type)) {
27
- constants.activeTimers.delete(timer.instance);
28
- cancelAnimationFrame(state.frame);
29
- if (type === "stop") {
30
- options.onAfter?.(false);
31
- }
32
- state.active = false;
33
- state.frame = void 0;
34
- state.paused = type === "pause";
35
- return type === "restart" ? work("start", timer, state, options) : timer.instance;
36
- }
37
- state.active = true;
38
- state.paused = false;
28
+ function ignore(type, state) {
29
+ return state.destroyed && type !== "stop" || (state.active ? constants.beginTypes.has(type) : constants.endTypes.has(type));
30
+ }
31
+ function run(timer, state, options) {
39
32
  let start;
40
- function step(now) {
33
+ return function step(now) {
41
34
  if (!state.active) {
42
35
  return;
43
36
  }
@@ -50,7 +43,7 @@ function work(type, timer, state, options) {
50
43
  finish(timer, state, options, false);
51
44
  return;
52
45
  }
53
- if (options.interval === constants.milliseconds || state.elapsed >= options.interval - 5) {
46
+ if (options.interval === constants.milliseconds || state.elapsed >= options.interval - constants.intervalBuffer) {
54
47
  if (options.count > -1) {
55
48
  state.callback(state.index);
56
49
  }
@@ -63,10 +56,32 @@ function work(type, timer, state, options) {
63
56
  }
64
57
  }
65
58
  state.frame = requestAnimationFrame(step);
59
+ };
60
+ }
61
+ function setState(type, state) {
62
+ const pausable = constants.pauseTypes.has(type);
63
+ state.elapsed = pausable ? state.elapsed : 0;
64
+ state.index = pausable ? state.index : 0;
65
+ state.total = pausable ? state.total : 0;
66
+ }
67
+ function stop(timer, state, options) {
68
+ endOrRestart("stop", timer, state, options);
69
+ }
70
+ function work(type, timer, state, options) {
71
+ if (ignore(type, state)) {
72
+ return timer.instance;
66
73
  }
74
+ setState(type, state);
75
+ if (constants.endOrRestartTypes.has(type)) {
76
+ return endOrRestart(type, timer, state, options);
77
+ }
78
+ state.active = true;
79
+ state.paused = false;
67
80
  constants.activeTimers.add(timer.instance);
68
- state.frame = requestAnimationFrame(step);
81
+ const runner = run(timer, state, options);
82
+ state.frame = requestAnimationFrame(runner);
69
83
  return timer.instance;
70
84
  }
71
85
 
86
+ exports.stop = stop;
72
87
  exports.work = work;
package/dist/work.js CHANGED
@@ -1,5 +1,15 @@
1
- import { beginTypes, endTypes, pauseTypes, endOrRestartTypes, activeTimers, milliseconds } from './constants.js';
1
+ import { endOrRestartTypes, activeTimers, beginTypes, endTypes, pauseTypes, milliseconds, intervalBuffer } from './constants.js';
2
2
 
3
+ function endOrRestart(type, timer, state, options) {
4
+ cancelAnimationFrame(state.frame);
5
+ if (type === "stop") {
6
+ options.onAfter?.(false);
7
+ }
8
+ state.active = false;
9
+ state.frame = void 0;
10
+ state.paused = type === "pause";
11
+ return type === "restart" ? work("start", timer, state, options) : timer.instance;
12
+ }
3
13
  function finish(timer, state, options, success) {
4
14
  activeTimers.delete(timer.instance);
5
15
  state.active = false;
@@ -11,29 +21,12 @@ function finish(timer, state, options, success) {
11
21
  options.onAfter?.(success);
12
22
  }
13
23
  }
14
- function work(type, timer, state, options) {
15
- if (state.destroyed && type !== "stop" || (state.active ? beginTypes.has(type) : endTypes.has(type))) {
16
- return timer.instance;
17
- }
18
- const pausable = pauseTypes.has(type);
19
- state.elapsed = pausable ? state.elapsed : 0;
20
- state.index = pausable ? state.index : 0;
21
- state.total = pausable ? state.total : 0;
22
- if (endOrRestartTypes.has(type)) {
23
- activeTimers.delete(timer.instance);
24
- cancelAnimationFrame(state.frame);
25
- if (type === "stop") {
26
- options.onAfter?.(false);
27
- }
28
- state.active = false;
29
- state.frame = void 0;
30
- state.paused = type === "pause";
31
- return type === "restart" ? work("start", timer, state, options) : timer.instance;
32
- }
33
- state.active = true;
34
- state.paused = false;
24
+ function ignore(type, state) {
25
+ return state.destroyed && type !== "stop" || (state.active ? beginTypes.has(type) : endTypes.has(type));
26
+ }
27
+ function run(timer, state, options) {
35
28
  let start;
36
- function step(now) {
29
+ return function step(now) {
37
30
  if (!state.active) {
38
31
  return;
39
32
  }
@@ -46,7 +39,7 @@ function work(type, timer, state, options) {
46
39
  finish(timer, state, options, false);
47
40
  return;
48
41
  }
49
- if (options.interval === milliseconds || state.elapsed >= options.interval - 5) {
42
+ if (options.interval === milliseconds || state.elapsed >= options.interval - intervalBuffer) {
50
43
  if (options.count > -1) {
51
44
  state.callback(state.index);
52
45
  }
@@ -59,10 +52,31 @@ function work(type, timer, state, options) {
59
52
  }
60
53
  }
61
54
  state.frame = requestAnimationFrame(step);
55
+ };
56
+ }
57
+ function setState(type, state) {
58
+ const pausable = pauseTypes.has(type);
59
+ state.elapsed = pausable ? state.elapsed : 0;
60
+ state.index = pausable ? state.index : 0;
61
+ state.total = pausable ? state.total : 0;
62
+ }
63
+ function stop(timer, state, options) {
64
+ endOrRestart("stop", timer, state, options);
65
+ }
66
+ function work(type, timer, state, options) {
67
+ if (ignore(type, state)) {
68
+ return timer.instance;
62
69
  }
70
+ setState(type, state);
71
+ if (endOrRestartTypes.has(type)) {
72
+ return endOrRestart(type, timer, state, options);
73
+ }
74
+ state.active = true;
75
+ state.paused = false;
63
76
  activeTimers.add(timer.instance);
64
- state.frame = requestAnimationFrame(step);
77
+ const runner = run(timer, state, options);
78
+ state.frame = requestAnimationFrame(runner);
65
79
  return timer.instance;
66
80
  }
67
81
 
68
- export { work };
82
+ export { stop, work };
package/package.json CHANGED
@@ -94,5 +94,5 @@
94
94
  },
95
95
  "type": "module",
96
96
  "types": "types/index.d.cts",
97
- "version": "0.30.0"
97
+ "version": "0.32.0"
98
98
  }
package/src/constants.ts CHANGED
@@ -1,30 +1,35 @@
1
1
  import type {WorkHandlerType} from './models';
2
2
  import type {Timer} from './timer';
3
3
 
4
- /**
5
- * Stepper to calculate the average refresh rate of the display
6
- */
7
- function stepper(now: DOMHighResTimeStamp): void {
8
- if (values.length === 7) {
9
- milliseconds = Math.floor(
10
- (values.slice(2).reduce((first, second) => first + second) / 5) * 2,
11
- ) / 2;
12
-
13
- last = undefined;
14
- values.length = 0;
15
- } else {
16
- last ??= now;
17
-
18
- const difference = now - last;
19
-
20
- if (difference > 0) {
21
- values.push(difference);
4
+ function calculate(): Promise<number> {
5
+ return new Promise(resolve => {
6
+ const values: number[] = [];
7
+
8
+ let last: DOMHighResTimeStamp | undefined;
9
+
10
+ function step(now: DOMHighResTimeStamp): void {
11
+ if (last != null) {
12
+ values.push(now - last);
13
+ }
14
+
15
+ last = now;
16
+
17
+ if (values.length >= 10) {
18
+ const median =
19
+ values
20
+ .sort()
21
+ .slice(2, -2)
22
+ .reduce((first, second) => first + second, 0) /
23
+ (values.length - 4);
24
+
25
+ resolve(median);
26
+ } else {
27
+ requestAnimationFrame(step);
28
+ }
22
29
  }
23
30
 
24
- last = now;
25
-
26
- requestAnimationFrame(stepper);
27
- }
31
+ requestAnimationFrame(step);
32
+ });
28
33
  }
29
34
 
30
35
  /**
@@ -37,6 +42,11 @@ export const activeTimers = new Set<Timer>();
37
42
  */
38
43
  export const beginTypes = new Set<WorkHandlerType>(['continue', 'start']);
39
44
 
45
+ /**
46
+ * Buffer value to use when evaluating if a specific time is within a certain range
47
+ */
48
+ export const intervalBuffer = 5;
49
+
40
50
  /**
41
51
  * Message to show when a when-timer is destroyed
42
52
  */
@@ -70,12 +80,11 @@ export const startedMessage = 'Timer has already been started';
70
80
 
71
81
  //
72
82
 
73
- const values: number[] = [];
74
- let last: DOMHighResTimeStamp | undefined;
75
-
76
83
  /**
77
84
  * A calculated average of the refresh rate of the display _(in milliseconds)_
78
85
  */
79
- export let milliseconds = Math.floor((1000 / 60) * 2) / 2;
86
+ export let milliseconds = 1000 / 60;
80
87
 
81
- requestAnimationFrame(stepper);
88
+ calculate().then(value => {
89
+ milliseconds = value;
90
+ });
package/src/delay.ts CHANGED
@@ -1,4 +1,4 @@
1
- import {milliseconds} from './constants';
1
+ import {intervalBuffer, milliseconds} from './constants';
2
2
  import {getValidNumber} from './get';
3
3
 
4
4
  /**
@@ -13,7 +13,10 @@ export function delay(time?: number): Promise<void> {
13
13
  function step(now: DOMHighResTimeStamp) {
14
14
  start ??= now;
15
15
 
16
- if (interval === milliseconds || now - start >= interval - 5) {
16
+ if (
17
+ interval === milliseconds ||
18
+ now - start >= interval - intervalBuffer
19
+ ) {
17
20
  resolve();
18
21
  } else {
19
22
  requestAnimationFrame(step);
package/src/repeat.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import {milliseconds} from './constants';
2
2
  import {getCallback, getValidNumber} from './get';
3
+ import './global';
3
4
  import {type RepeatOptions, TimerTrace} from './models';
4
5
  import {Timer} from './timer';
5
- import {work} from './work';
6
6
 
7
7
  /**
8
8
  * Create a repeating timer
@@ -13,7 +13,6 @@ export function repeat(
13
13
  ): Timer {
14
14
  return new Timer(
15
15
  'repeat',
16
- work,
17
16
  {
18
17
  callback: getCallback(callback),
19
18
  trace: new TimerTrace().stack,
package/src/timer.ts CHANGED
@@ -1,10 +1,11 @@
1
+ import {noop} from '@oscarpalmer/atoms/function';
1
2
  import type {
2
3
  TimerOptions,
3
4
  TimerState,
4
5
  TimerType,
5
- WorkHandler,
6
6
  WorkHandlerType,
7
7
  } from './models';
8
+ import {stop, work} from './work';
8
9
 
9
10
  export class Timer {
10
11
  private declare readonly $timer: TimerType;
@@ -43,7 +44,6 @@ export class Timer {
43
44
 
44
45
  constructor(
45
46
  type: TimerType,
46
- protected readonly worker: WorkHandler,
47
47
  state: Pick<TimerState, 'callback' | 'trace'>,
48
48
  protected readonly options: TimerOptions,
49
49
  start: boolean,
@@ -79,7 +79,22 @@ export class Timer {
79
79
  destroy(): void {
80
80
  this.state.destroyed = true;
81
81
 
82
- this.#work('stop');
82
+ this.options.onAfter = noop;
83
+ this.options.onError = noop;
84
+ this.state.callback = noop;
85
+
86
+ if (!globalThis._oscarpalmer_timer_debug) {
87
+ this.state.trace = undefined;
88
+ }
89
+
90
+ stop(
91
+ {
92
+ instance: this,
93
+ type: this.$timer,
94
+ },
95
+ this.state,
96
+ this.options,
97
+ );
83
98
  }
84
99
 
85
100
  /**
@@ -111,7 +126,7 @@ export class Timer {
111
126
  }
112
127
 
113
128
  #work(type: WorkHandlerType): Timer {
114
- return this.worker(
129
+ return work(
115
130
  type,
116
131
  {
117
132
  instance: this,
package/src/wait.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import {milliseconds} from './constants';
2
2
  import {getCallback, getValidNumber} from './get';
3
+ import './global';
3
4
  import {TimerTrace} from './models';
4
5
  import {Timer} from './timer';
5
- import {work} from './work';
6
6
 
7
7
  /**
8
8
  * Create a waiting timer
@@ -12,7 +12,6 @@ import {work} from './work';
12
12
  export function wait(callback: () => void, time?: number): Timer {
13
13
  return new Timer(
14
14
  'wait',
15
- work,
16
15
  {
17
16
  callback: getCallback(callback),
18
17
  trace: new TimerTrace().stack,