import { Controller } from "stimulus"; import Rails from "@rails/ujs"; export default class extends Controller { static targets = [ "timer" ]; static values = { start: Number, } initialize() { this.counter = this.startValue; this.timerTarget.textContent = this.counter; } connect() { this.startUpdating(); } disconnect() { this.stopUpdating(); } startUpdating() { this.timerInterval = setInterval(() => { if (this.counter > 0) { this.timerTarget.textContent = this.counter.toString(); this.counter--; } else if (this.counter === 0) { Rails.ajax({ type: "POST", url: "/finish_activity", }); } }, 1000); } stopUpdating() { if (this.timerInterval) { clearInterval(this.timerInterval); } } }