scriptable-testlab
Version:
A lightweight, efficient tool designed to manage and update scripts for Scriptable.
86 lines (74 loc) • 1.68 kB
text/typescript
import {AbsTimer} from 'scriptable-abstract';
interface TimerState {
timeInterval: number;
repeats: boolean;
running: boolean;
}
/**
* Mock implementation of Scriptable's Timer
* Used to schedule code execution after a delay
*/
export class MockTimer extends AbsTimer<TimerState> {
private timerId: NodeJS.Timeout | null = null;
constructor() {
super({
timeInterval: 0,
repeats: false,
running: false,
});
}
/**
* Schedule a function to be called after a delay
* @param callback Function to be called
*/
schedule(callback: () => void): void {
const ms = this.timeInterval * 1000;
if (this.repeats) {
this.timerId = setInterval(callback, ms);
} else {
this.timerId = setTimeout(callback, ms);
}
this.setState({running: true});
}
/**
* Invalidates the timer, preventing it from firing
*/
invalidate(): void {
if (this.timerId) {
clearTimeout(this.timerId);
clearInterval(this.timerId);
this.timerId = null;
}
this.setState({running: false});
}
/**
* Whether the timer is currently running
*/
get isRunning(): boolean {
return this.state.running;
}
/**
* Time interval in seconds
*/
get timeInterval(): number {
return this.state.timeInterval;
}
/**
* Sets the time interval in seconds
*/
set timeInterval(value: number) {
this.setState({timeInterval: value});
}
/**
* Whether the timer repeats
*/
get repeats(): boolean {
return this.state.repeats;
}
/**
* Sets whether the timer repeats
*/
set repeats(value: boolean) {
this.setState({repeats: value});
}
}