Created
May 10, 2022 05:45
-
-
Save ollie314/3452f2ba0c19e701f483113be874318f to your computer and use it in GitHub Desktop.
Elm Stopwatch sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Browser | |
import Html exposing (..) | |
import Html.Events exposing (onClick) | |
import Task | |
import Time | |
main = | |
Browser.element | |
{ init = init | |
, view = view | |
, update = update | |
, subscriptions = subscriptions | |
} | |
type StopwatchStatus = Stopped | Started | |
type alias Model = | |
{ ticks : Int | |
, status: StopwatchStatus | |
} | |
init : () -> (Model, Cmd Msg) | |
init _ = | |
( {ticks = 0, status = Stopped} | |
, Task.perform Reset Time.now) | |
type Msg | |
= Start | |
| Stop | |
| Tick Time.Posix | |
| Reset Time.Posix | |
update : Msg -> Model -> (Model, Cmd Msg) | |
update msg model = | |
case msg of | |
Tick t -> | |
if model.status == Started then | |
( { model | ticks = model.ticks + 1 } | |
, Cmd.none) | |
else | |
( model, Cmd.none ) | |
Stop -> | |
( { model | status = Stopped } | |
, Cmd.none | |
) | |
Start -> | |
( { model | status = Started } | |
, Cmd.none | |
) | |
Reset t -> | |
( { model | status = Stopped, ticks = 0} | |
, Cmd.none | |
) | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
Time.every 1000 Tick | |
view : Model -> Html Msg | |
view model = | |
let | |
ticks = String.fromInt (model.ticks) | |
in | |
div [] | |
[ h1 [] [ text ("nbSeconds" ++ ": " ++ ticks) ] | |
, button [ onClick Start] [text "Start"] | |
, button [ onClick Stop] [text "Stop"] | |
, button [ onClick (Reset (Time.millisToPosix 0))] [text "Reset"] | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment