在Elm中立即启动计时器
我希望下面的代码在打开和关闭计时器时异步增加计数。但它总是同步工作(增量为2) 如何使其异步 编辑:可能是由于我的英语能力不足,这个问题似乎经常被误解。我希望实现的行为与我的答案完全相同。关键是,两个计时器应该通过切换分别增加计数在Elm中立即启动计时器,elm,Elm,我希望下面的代码在打开和关闭计时器时异步增加计数。但它总是同步工作(增量为2) 如何使其异步 编辑:可能是由于我的英语能力不足,这个问题似乎经常被误解。我希望实现的行为与我的答案完全相同。关键是,两个计时器应该通过切换分别增加计数 解决这个问题的方法如下,但这当然是不可取的。我想尽可能多地使用其他解决方案。请为我提供可靠的方法 import Html exposing (program, div, button, text) import Html.Events exposing (onClic
解决这个问题的方法如下,但这当然是不可取的。我想尽可能多地使用其他解决方案。请为我提供可靠的方法
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,并且始终允许手动递增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)
我对我的问题作了补充澄清。有一个答案与您的答案类似。为了清楚起见:您希望显示的输出为:1、2、3、4,而不管model.on是否为真。model.on只应根据切换实际发生的时间影响显示更改的速度。但问题是当model.on为真时,它显示1、3、5。而不是1,2,3,4,5在一个不同的速度比以前。如果我正确理解了你的问题,请告诉我。@Jigar是的。这就是我的意思。
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)