summaryrefslogtreecommitdiff
path: root/app/javascript/controllers/activities/timer_controller.js
blob: 11057c0a34db18664157b942b3616af0dfd817ba (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
import { Controller } from "stimulus";
import Rails from "@rails/ujs";

export default class extends Controller {
  static targets = [ "timer" ];

  static values = {
    start: Number,
  }

  initialize() {
    this.counter = this.startValue;
    this.timerTarget.textContent = this.counter;
  }

  connect() {
    this.startUpdating();
  }

  disconnect() {
    this.stopUpdating();
  }

  startUpdating() {
    this.timerInterval = setInterval(() => {
      if (this.counter > 0) {
        this.timerTarget.textContent = this.counter.toString();
        this.counter--;
      } else if (this.counter === 0) {
        Rails.ajax({
          type: "POST",
          url: "/finish_activity",
        });
      }
    }, 1000);
  }

  stopUpdating() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
  }
}