import { Controller } from "stimulus"; import Rails from "@rails/ujs"; export default class extends Controller { static targets = [ "timer" ]; static values = { start: Number, postUrl: String, } initialize() { this.counter = this.startValue; this.timerTarget.textContent = this.counter; this.postFailures = 0; } connect() { this.startUpdating(); } disconnect() { this.stopUpdating(); } startUpdating() { let controller = this; this.timerInterval = setInterval(() => { if (controller.postFailures >= 5) { alert("An error occurred. Please submit a bug report, explaining what you were doing when it occurred."); clearInterval(controller.timerInterval); return; } if (controller.counter > 0) { controller.timerTarget.textContent = controller.counter.toString(); controller.counter--; } else if (this.counter <= 0) { Rails.ajax({ type: "POST", url: controller.postUrlValue, success: () => { controller.postFailures = 0; }, error: () => { controller.postFailures++; }, }); } }, 1000); } stopUpdating() { if (this.timerInterval) { clearInterval(this.timerInterval); } } }