Skip to content

Instantly share code, notes, and snippets.

@ollie314
Created May 10, 2022 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ollie314/3452f2ba0c19e701f483113be874318f to your computer and use it in GitHub Desktop.
Save ollie314/3452f2ba0c19e701f483113be874318f to your computer and use it in GitHub Desktop.
Elm Stopwatch sample
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