[Functional Programming] Building a Timer UI by Composing Callbacks
Controlling when a broadcaster starts and stops gives you complete control over your broadcasters. This let's you hook multiple pieces of UI together to offer to the user and allow them to manage the behaviors of your application. This lesson walks through creating a timer using a startWhen and a stopWhen operator which are hooked into buttons.
Think of some other scenarios where have beginnings and ends controlled by events. For example, a mouse drag that starts with a mouse down and ends with a mouse up
import { curry, pipe } from "ramda"; document.getElementById("app").innerHTML = ` <h1>Hello Parcel!</h1> <div> <button id="start">Start</button> <button id="stop">Stop</button> </div> `; const addListener = (selector, eventType) => (listener) => { const element = document.querySelector(selector); element.addEventListener(eventType, listener); return () => { element.removeEventListener(eventType, listener); }; }; const createInterval = curry((time, listener) => { let i = 0; const id = setInterval(() => { listener(i++); }, time); return () => { clearInterval(id); }; }); let startClick = addListener("#start", "click"); let stopClick = addListener("#stop", "click"); let timer = createInterval(100); // A event happen to trigger B event let startWhen = (whenBroadcaster) => (mainBroadcaster) => (listener) => { let cancelMain; let cancelWhen; cancelWhen = whenBroadcaster((whenValue) => { if (cancelMain) cancelMain(); cancelMain = mainBroadcaster((value) => {
if (value === done) {
if (whenValue === done) {
listener(done);
}
return
}
listener(value) }); }); return () => { cancelMain(); cancelWhen(); }; }; let stopWhen = (whenBroadcaster) => (mainBroadcaster) => (listener) => { let cancelMain = mainBroadcaster(listener); let cancelWhen = whenBroadcaster((value) => { cancelMain(); }); return () => { cancelMain(); cancelWhen(); }; }; const operators = pipe(stopWhen(stopClick), startWhen(startClick)); operators(timer)(console.log); // startWhen(startClick)(stopWhen(stopClick)(timer)) (console.log)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-11-02 [MDX] Build a Custom Provider Component for MDX Deck
2018-11-02 [WASM + Rust] Debug a WebAssembly Module Written in Rust using console.log
2017-11-02 [AngularFire] Firebase OAuth Login With Custom Firestore User Data
2017-11-02 [AngularFire2 & Firestore] Example for collection and doc
2015-11-02 [Ruby] LEVEL 2 Methods and Classes
2015-11-02 [Rails Level 2] Ground up
2015-11-02 [AngularJS] 5 simple ways to speed up your AngularJS application