import {Controller} from "stimulus"; import Rails from "@rails/ujs"; export default class extends Controller { static targets = [ "timer", "progressBar" ]; static values = { timeRemaining: Number, activityDuration: Number, postUrl: String, } connect() { App.timerWorker.postMessage({ "run_flag": true }); this.timerTarget.textContent = Math.ceil(this.timeRemainingValue); this.postFailures = 0; let controller = this; App.timerWorker.onmessage = function() { if (controller.timeRemainingValue > 0) { controller.timeRemainingValue = controller.timeRemainingValue - 0.01; } if (controller.timeRemainingValue > 0) { controller.timerTarget.textContent = Math.ceil(controller.timeRemainingValue).toString(); controller.progressBarTarget.style.width = `${(1 - (controller.timeRemainingValue / controller.activityDurationValue)) * 100}%`; } else { App.timerWorker.postMessage({ "run_flag": false }); controller.finishActivity(); } } } finishActivity() { let controller = this; Rails.ajax({ type: "POST", url: controller.postUrlValue, success: () => { this.postFailures = 0; App.timerWorker.postMessage({ "set_timeout": 10 }); }, error: (e, xhr) => { this.postFailures++; if (this.postFailures < 3) { App.timerWorker.postMessage({ "run_flag": true }); App.timerWorker.postMessage({ "set_timeout": 1000 }); } else if (this.postFailures < 5 || xhr === "") { App.timerWorker.postMessage({ "run_flag": true }); App.timerWorker.postMessage({ "set_timeout": 60000 }); } }, }); } }