Created
January 10, 2020 14:49
-
-
Save ababup1192/0ae63fa86d89dfe74a47a8d0995b3999 to your computer and use it in GitHub Desktop.
Timer
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
module Main exposing (main) | |
import Browser | |
import Browser.Events exposing (onAnimationFrame) | |
import Html exposing (Html, button, div, p, text) | |
import Html.Events exposing (onClick) | |
import Task | |
import Time | |
main = | |
Browser.element { init = init, update = update, view = view, subscriptions = subscriptions } | |
type alias Model = | |
{ stoppedTime : Int | |
, time : Int | |
, lastStartedAtMaybe : Maybe Int | |
} | |
init : () -> ( Model, Cmd Msg ) | |
init _ = | |
( { stoppedTime = 0, time = 0, lastStartedAtMaybe = Nothing }, Cmd.none ) | |
type Msg | |
= Tick Time.Posix | |
| StartStop | |
| SetLastStartedAt Time.Posix | |
| SetStoppedTime Int Time.Posix | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
let | |
calcTime now lastStartedAt = | |
model.stoppedTime + Time.posixToMillis now - lastStartedAt | |
in | |
case msg of | |
Tick now -> | |
( { model | |
| time = | |
case model.lastStartedAtMaybe of | |
Just lastStartedAt -> | |
calcTime now lastStartedAt | |
Nothing -> | |
model.stoppedTime | |
} | |
, Cmd.none | |
) | |
StartStop -> | |
case model.lastStartedAtMaybe of | |
Just lastStartedAt -> | |
( model, Task.perform (SetStoppedTime lastStartedAt) Time.now ) | |
Nothing -> | |
( model, Task.perform SetLastStartedAt Time.now ) | |
SetStoppedTime lastStartedAt now -> | |
( { model | |
| stoppedTime = | |
calcTime now lastStartedAt | |
, lastStartedAtMaybe = Nothing | |
} | |
, Cmd.none | |
) | |
SetLastStartedAt now -> | |
( { model | lastStartedAtMaybe = Just <| Time.posixToMillis now }, Cmd.none ) | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ p [] [ text <| "timer (sec): " ++ (String.fromInt <| model.time // 1000) ] | |
, p [] [ text <| "timer (ms): " ++ String.fromInt model.time ] | |
, button [ onClick StartStop ] | |
[ text <| | |
case model.lastStartedAtMaybe of | |
Just _ -> | |
"stop" | |
Nothing -> | |
"start" | |
] | |
] | |
subscriptions : Model -> Sub Msg | |
subscriptions _ = | |
onAnimationFrame Tick |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment