Skip to content

Instantly share code, notes, and snippets.

@shritesh
Last active March 19, 2020 16:13
Show Gist options
  • Select an option

  • Save shritesh/7e7d31488c04ba118c3e15d5e65607d5 to your computer and use it in GitHub Desktop.

Select an option

Save shritesh/7e7d31488c04ba118c3e15d5e65607d5 to your computer and use it in GitHub Desktop.
ReasonML p5.js Stopwatch
type p5;
type sketch = {
mutable setup: unit => unit,
mutable draw: unit => unit,
};
type button;
type state =
| Initializing
| NotStarted(button)
| Running(button, int)
| Stopped(button, int);
[@bs.module] [@bs.new] external createP5: (sketch => unit) => p5 = "p5";
[@bs.send] external createCanvas: (sketch, int, int) => unit = "createCanvas";
[@bs.send] external noCanvas: sketch => unit = "noCanvas";
[@bs.send] external millis: sketch => int = "millis";
[@bs.send] external createButton: (sketch, string) => button = "createButton";
[@bs.send] external html: (button, string) => unit = "html";
[@bs.send]
external mousePressed: (button, unit => unit) => unit = "mousePressed";
[@bs.send] external nfc: (sketch, float, int) => string = "nfc";
let makeSketch = s => {
let appState = ref(Initializing);
let btnPressed = () => {
switch (appState^) {
| NotStarted(btn) => appState := Running(btn, millis(s))
| Running(btn, time) => appState := Stopped(btn, time)
| Stopped(btn, _) =>
appState := NotStarted(btn);
html(btn, "Start");
| _ => ()
};
};
s.setup = (
() => {
noCanvas(s);
let btn = createButton(s, "Start");
mousePressed(btn, btnPressed);
appState := NotStarted(btn);
}
);
s.draw = (
() => {
switch (appState^) {
| Running(btn, time) =>
let seconds = float(millis(s) - time) /. 1000.0;
let str = nfc(s, seconds, 2);
html(btn, str ++ " Seconds");
| _ => ()
};
}
);
};
createP5(makeSketch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment