Search code examples
thread-sleepelm

Effects.tick replacement for elm 0.17


As it's stated in the upgrade guide, Effects is being replaced by this new Applicative Functor-like thing Cmd. I don't see any trace of a clue as to where Effects.tick might be hiding, or how it could be reimplemented.

From the looks of things, Process.sleep might be the right answer, something like

Task.perform errorHandler (\x -> x) <| Process.sleep
                                    <| 500 * Time.millisecond

would allow the process to wait 500 milliseconds before issuing the next message / action. I'm just not sure if this is what will replace Effects.tick in the long run though.


Solution

  • Effect.tick functionality is replaced by AnimationFrame.

    You basically subscribe to a set of msg of either times or diffs. And react accordingly.

    import Html exposing (..)
    import Html.App as App 
    import AnimationFrame 
    import Time exposing (Time, second)
    
    main = 
      App.program 
        { init = Model 0 0 ! []
        , update = \msg model -> update msg model ! []
        , view = view 
        , subscriptions = \_ -> AnimationFrame.diffs identity}
    
    type alias Model = 
      { timeSinceLastIncrement : Time 
      , counter : Int }
    
    incrementTime = 1*second
    
    update diff {timeSinceLastIncrement, counter} = 
      if timeSinceLastIncrement > incrementTime then 
        Model 0 (counter+1)
      else
        Model (timeSinceLastIncrement+diff) counter
    
    view {counter} = 
      div [] [text (toString counter)] 
    

    I've chosen to send the Time diffs directly as messages and to unpack the structure of the model in both update and view for easier access to components. In a more complex app you will probably have something like a Tick Time message.