培根中的控制流程.js,如何在给定时间做某事

Control flow in bacon.js, how to do something at a given time

本文关键字:定时间 控制流 js      更新时间:2023-09-26

所以我对函数式编程范式相当陌生,尤其是培根.js和FRP新手。我需要一些关于如何在FRP中概念化控制流的建议。我在事件流中有一个倒计时到零的计时器。当它达到零时,我想隐藏 HTML 计时器计数器并停止事件流。

timer.coffee

# decrement function
dec = (x,y) ->
    x-y
# Create a timer counting down from 100 every 10th millisecond
timer = Bacon.interval(10, 1).scan(100, dec)
timer.onValue (e) ->
  # output the current timer value to the DOM
  $("#timer").text(e)
  # if the timer has reached 0, hide the DOM object 
  $("#timer").hide() if e is 0

timer.html

<body>
  <div id="timer"></div>
</body>

我真的应该使用 if/else 来检查值并调用函数,就像我在 onValue() 中所做的那样吗?不知何故,感觉好像我做错了。当我对事件流感到满意时,如何停止/关闭它?

定义流时,请包含 takeWhile 以在某个条件下结束流。您可以使用 onEnd 在流结束上分配副作用。