From b6955ee9aa0058f64f6e3b6314d2b7358939bc2e Mon Sep 17 00:00:00 2001 From: David Gay Date: Mon, 7 Jun 2021 21:00:17 -0400 Subject: Implement web worker to keep timer running even when page is inactive --- app/javascript/controllers/timer_controller.js | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) (limited to 'app/javascript/controllers/timer_controller.js') diff --git a/app/javascript/controllers/timer_controller.js b/app/javascript/controllers/timer_controller.js index 4888f6a..f6ba4f3 100644 --- a/app/javascript/controllers/timer_controller.js +++ b/app/javascript/controllers/timer_controller.js @@ -11,15 +11,12 @@ export default class extends Controller { } connect() { - if (!this.timerInterval) this.startUpdating(); + App.timerWorker.postMessage({ "run_flag": true }); this.timerTarget.textContent = Math.ceil(this.timeRemainingValue); this.postFailures = 0; - } - startUpdating() { let controller = this; - controller.timerInterval = setInterval(() => { - + App.timerWorker.onmessage = function() { if (controller.timeRemainingValue > 0) { controller.timeRemainingValue = controller.timeRemainingValue - 0.01; } @@ -28,11 +25,10 @@ export default class extends Controller { controller.timerTarget.textContent = Math.ceil(controller.timeRemainingValue).toString(); controller.progressBarTarget.style.width = `${(1 - (controller.timeRemainingValue / controller.activityDurationValue)) * 100}%`; } else { - clearInterval(controller.timerInterval); - controller.timerInterval = null; + App.timerWorker.postMessage({ "run_flag": false }); controller.finishActivity(); } - }, 10); + } } finishActivity() { -- cgit v1.2.3