summaryrefslogtreecommitdiff
path: root/app/javascript/controllers/timer_controller.js
blob: ef741bf57ee11e0e3c9b37e51d2668337ef4844a (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
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;
    this.startUpdating();
  }

  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.counter--;

      if (controller.counter > 0) {
        controller.timerTarget.textContent = controller.counter.toString();
      } else {
        Rails.ajax({
          type: "POST",
          url: controller.postUrlValue,
          success: () => {
            controller.postFailures = 0;
          },
          error: () => {
            controller.postFailures++;
          },
        });
      }
    }, 1000);
  }
}