summaryrefslogtreecommitdiff
path: root/events/timer.ml
blob: 0a75e1293a16e9b56966206da79065f45e3ce98b (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
open Brr_note_kit

type t =
  { mutable id : Brr.G.timer_id
  ; send : float Note.E.send
  ; mutable counter : Time.counter
  }

let create
  : unit -> (t * Brr_note_kit.Time.span Note.E.t)
  = fun () ->
    let event, send = Note.E.create ()
    and counter = (Time.counter ()) in
    {id = (-1); send; counter}, event

let stop
  : t -> unit
  = fun {id; _} ->
    Brr.G.stop_timer id

let start
  : t -> float -> unit
  = fun t d ->
    let {id; send; _} = t in
    t.counter <- Time.counter ();


    Brr.G.stop_timer id;
    let timer_id = Brr.G.set_interval
        ~ms:(int_of_float @@ d *. 1000.)
        (fun () ->

           let span = Time.counter_value t.counter in
           t.counter <- Time.counter ();
           send span) in
    ignore @@ Brr.G.set_timeout ~ms:0 (fun () ->  send 0.);
    t.id <- timer_id


let delay : t -> float
  = fun t -> Time.counter_value t.counter