denoland / roll-your-own-javascript-runtime

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to implement setInterval?

adhamsalama opened this issue · comments

Hello.

I had so much fun following this tutorial.

I implemented setTimeout using the answer to my question here denoland/deno#19231

#[op]
async fn op_set_timeout(delay: u64) -> Result<(), AnyError> {
    tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
    Ok(())
}

This works fine because it does nothing but wait and then return to JavaScript where we can execute the callback.

But how could we implement setInterval?
We need to execute the JavaScript callback after every delay, and also return a timer ID so that JavaScript could cancel it later. I don't get how to do all of that in a single function.

So, could you please help me? Thanks in advance!

Generally when implementing something like setInterval, you'd want to learn towards providing a stream to JS. You'd provide an async op that picks off the next item from a Stream's next function and just call that repeatedly.

@mmastrac Do you have any extra resources/documentation on how someone would do that? I would love to read more about this.

I want to try to implement as funcionality as I can, for education purposes.