立即在Elm启动计时器

时间:2017-03-26 08:07:42

标签: elm

我对以下代码的期望是在我打开和关闭计时器时异步递增计数。但它始终同步工作(增加2)。

如何让它异步?

编辑:可能由于我的英语能力不足,似乎这个问题经常被误解。我希望实现与我的答案完全相同。关键是,两个计时器应该通过切换分别增加计数。

import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every second (always Increment)
  , if model.on then every second (always Increment) else Sub.none
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "-" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Increment | Toggle

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)
    Toggle ->
      ({model | on = not model.on}, Cmd.none)

2 个答案:

答案 0 :(得分:0)

哈希这个问题如下,但它当然不可取。我想尽可能地使用其他解决方案。请为我提供可靠的方法。

import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every (second + 0.0000000001) (always Increment)
  , if model.on then every second (always Increment) else Sub.none
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "-" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Increment | Toggle

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)
    Toggle ->
      ({model | on = not model.on}, Cmd.none)

答案 1 :(得分:0)

这是一个版本,在on时每秒计数1次,并且总是允许手动递增1。

import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every second (always Tick)
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "Toggle" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Tick | Toggle | Increment

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)

    Tick ->
      case model.on of
        True ->
          ({model | cnt = model.cnt + 1}, Cmd.none)
        False ->
          (model, Cmd.none)

    Toggle ->
      ({model | on = not model.on}, Cmd.none)