summaryrefslogtreecommitdiff
path: root/app/javascript/controllers/timer_controller.js
blob: 5190a791b8de304302bb6807be7aa3bfb69822ae (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
57
58
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);
    }
  }
}