I am trying to pick up PureScript. Something I do a lot in JS is the following:
let start;
function step(timestamp) {
if (start === undefined)
start = timestamp;
const elapsed = timestamp - start;
console.log(elapsed);
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
I've managed to get a loop going like this:
main :: Effect Unit
main = do
w <- window
step w
step :: Window -> Effect Unit
step w = do
log "timestamp?!"
requestAnimationFrame (step w) w $> unit
However, I don't know where to go from here, I'm not even sure how I could get step
to take a timestamp parameter with requestAnimationFrame
's signature in PureScript:
Effect Unit -> Window -> Effect RequestAnimationFrameId
The library has requestAnimationFrame
defined without a parameter for some reason, so no luck there (consider submitting a pull request to the library).
If I know more details about the ultimate purpose of doing that, I might recommend a better approach. Chances are, in PureScript you don't have to use requestAnimationFrame
at all. PureScript has Aff
for example, that might be better suited.
But without knowing the specifics, if I had to translate that JS code to PureScript as closely as possible, I would recommend defining your own FFI binding for requestAnimationFrame
.
In your foreign module, MyModule.js
:
export function requestAnimationFrame(f) {
window.requestAnimationFrame(ts => f(ts)())
}
In your PureScript module, MyModule.purs
:
foreign import requestAnimationFrame :: (Int -> Effect Unit) -> Effect Unit
And that's it. Now you can call your own version of requestAnimationFrame
and pass it a function that takes a parameter:
step :: Window -> Int -> Effect Unit
step w ts = do
log (show ts)
requestAnimationFrame (step w)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.