webtools/site/mental-arithmatic/scripts/countdown.js

35 lines
1,018 B
JavaScript
Raw Permalink Normal View History

2026-01-16 11:12:30 +00:00
import { Controller } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js";
export class CountdownController extends Controller {
static targets = ["countdown", "fakeinput"];
start() {
this.element.classList.remove('hidden');
this._countdown = 3;
this.countdownTarget.innerText = this._countdown;
this._tickInterval = window.setInterval(this._tick.bind(this), 1000);
window.setTimeout(() => {
this.fakeinputTarget.focus();
}, 1);
}
_tick() {
this._countdown -= 1;
if (this._countdown === 0) {
this.countdownTarget.innerText = "GO!";
} else if (this._countdown < 0) {
window.clearInterval(this._tickInterval);
this._startActualGame();
} else {
this.countdownTarget.innerText = this._countdown;
}
}
_startActualGame() {
this.element.classList.add('hidden');
window.dispatchEvent(new CustomEvent("startGame"));
}
}