如何在Elm中实现setTimeout的行为 [英] How to achieve behavior of setTimeout in Elm

查看:77
本文介绍了如何在Elm中实现setTimeout的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Elm编写一个网络游戏,其中包含许多与时间有关的事件,并且我正在寻找一种在特定时间延迟安排事件的方法。

I'm writing a web game in Elm with lot of time-dependent events and I'm looking for a way to schedule an event at a specific time delay.

在JavaScript中,我使用了 setTimeout(f,timeout),这显然效果很好,但是出于各种原因,我想避免使用JavaScript代码,而只使用Elm。

In JavaScript I used setTimeout(f, timeout), which obviously worked very well, but - for various reasons - I want to avoid JavaScript code and use Elm alone.

我知道我可以订阅 Tick 以特定的间隔并接收时钟滴答,但这不是我想要的-我的延迟没有合理的公分母(例如,两个延迟分别是30ms和500ms),并且我想避免不得不处理很多不必要的事情滴答声。

I'm aware that I can subscribe to Tick at specific interval and recieve clock ticks, but this is not what I want - my delays have no reasonable common denominator (for example, two of the delays are 30ms and 500ms), and I want to avoid having to handle a lot of unnecessary ticks.

我还遇到了任务过程 -似乎通过使用它们,我可以通过 Task.perform failHandler successHandler(Process.sleep Time.second)以某种方式实现所需的功能。

I also came across Task and Process - it seems that by using them I am somehow able to what I want with Task.perform failHandler successHandler (Process.sleep Time.second).

这可行,但不是很直观-我的处理程序只是忽略所有可能的输入并发送相同的消息。而且,我不希望超时会失败,因此创建失败处理程序的感觉就像是在馈送库一样,这并不是我期望的那样优雅的语言。

This works, but is not very intuitive - my handlers simply ignore all possible input and send same message. Moreover, I do not expect the timeout to ever fail, so creating the failure handler feels like feeding the library, which is not what I'd expect from such an elegant language.

是否有类似 Task.delayMessage时间消息的内容,它可以完全满足我的需要(向我发送副本在指定的时间后传递其消息参数),还是我必须为此做一个自己的包装?

Is there something like Task.delayMessage time message which would do exactly what I need to (send me a copy of its message argument after specified time), or do I have to make my own wrapper for it?

推荐答案

起初并不明显的是,订阅可以根据模型进行更改。每次更新后都会对它们进行有效评估。您可以使用此事实以及模型中的某些字段来控制随时处于活动状态的订阅。

One thing that may not be obvious at first is the fact that subscriptions can change based on the model. They are effectively evaluated after every update. You can use this fact, coupled with some fields in your model, to control what subscriptions are active at any time.

这里是一个允许可变光标闪烁间隔

subscriptions : Model -> Sub Msg
subscriptions model =
    if model.showCursor
        then Time.every model.cursorBlinkInterval (always ToggleCursor)
        else Sub.none

如果我理解您的担忧,这应该可以克服处理不必要的滴答声的可能性。您可以使用 Sub.batch 进行多个不同时间间隔的订阅。

If I understand your concerns, this should overcome the potential for handling unnecessary ticks. You can have multiple subscriptions of different intervals by using Sub.batch.

这篇关于如何在Elm中实现setTimeout的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆