@stimulus-library/controllers
Version:
A library of useful controllers for Stimulus
52 lines (51 loc) • 1.53 kB
JavaScript
import { BaseController } from "@stimulus-library/utilities";
import { useInterval } from "@stimulus-library/mixins";
export class ClockController extends BaseController {
get _tickInterval() {
if (this.hasMillisecondsTarget) {
return 1;
}
else if (this.hasSecondsTarget) {
return 1000;
}
else if (this.hasMinutesTarget) {
return 15000;
}
else {
return 300000;
}
}
connect() {
requestAnimationFrame(() => {
useInterval(this, this._tick, this._tickInterval);
});
}
_tick() {
const current = new Date();
if (this.hasHoursTarget) {
this.hoursTarget.innerHTML = current
.getHours()
.toString()
.padStart(2, "0");
}
if (this.hasMinutesTarget) {
this.minutesTarget.innerHTML = current
.getMinutes()
.toString()
.padStart(2, "0");
}
if (this.hasSecondsTarget) {
this.secondsTarget.innerHTML = current
.getSeconds()
.toString()
.padStart(2, "0");
}
if (this.hasMillisecondsTarget) {
this.millisecondsTarget.innerHTML = current
.getMilliseconds()
.toString()
.padStart(3, "0");
}
}
}
ClockController.targets = ["hours", "minutes", "seconds", "milliseconds"];