summaryrefslogtreecommitdiff
path: root/app/javascript/controllers/timer_controller.js
blob: 4888f6a7be642835e7036687b0fd39691d21ceea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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() {
    if (!this.timerInterval) this.startUpdating();
    this.timerTarget.textContent = Math.ceil(this.timeRemainingValue);
    this.postFailures = 0;
  }

  startUpdating() {
    let controller = this;
    controller.timerInterval = setInterval(() => {

      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 {
        clearInterval(controller.timerInterval);
        controller.timerInterval = null;
        controller.finishActivity();
      }
    }, 10);
  }

  finishActivity() {
    let controller = this;
    Rails.ajax({
      type: "POST",
      url: controller.postUrlValue,
      success: () => {
        this.postFailures = 0;
      },
      error: (e, xhr) => {
        this.postFailures++;
        if (this.postFailures < 3) {
          setTimeout(controller.finishActivity, 1000); // 1 second
        } else if (xhr === "") {
          setTimeout(controller.finishActivity, 60000); // 1 minute
        }
      },
    });
  }
}