Skip to content

Commit

Permalink
SetTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
losfair committed Jan 4, 2021
1 parent 02848d4 commit 55452c6
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 2 deletions.
80 changes: 80 additions & 0 deletions librt/src/std.js
Expand Up @@ -81,6 +81,86 @@ export function dispatchEvent(event) {
}
}

/**
* @type {Map<number, boolean>}
*/
let inflightTimeouts = new Map();
let nextTimeoutId = 1;

/**
*
* @param {function} callback
* @param {number} ms
* @param {any[]} args
* @param {boolean} isInterval
* @returns {number}
*/
function scheduleTimeoutOrInterval(callback, ms, args, isInterval) {
let id = nextTimeoutId;
nextTimeoutId++;
inflightTimeouts.set(id, isInterval);

function onFire() {
if(inflightTimeouts.has(id)) {
let isInterval = inflightTimeouts.get(id);
if(isInterval) {
schedule(ms, onFire);
} else {
inflightTimeouts.delete(id);
}
callback.call(this, args);
}
}

function schedule(ms, callback) {
_callService({
Async: {
SetTimeout: ms,
}
}, callback);
}

schedule(ms, onFire);
return id;
}

/**
*
* @param {function} callback
* @param {number} ms
* @param {...any} args
* @returns {number}
*/
export function setTimeout(callback, ms, ...args) {
return scheduleTimeoutOrInterval(callback, ms, args, false);
}
/**
*
* @param {function} callback
* @param {number} ms
* @param {...any} args
* @returns {number}
*/
export function setInterval(callback, ms, ...args) {
return scheduleTimeoutOrInterval(callback, ms, args, true);
}

/**
*
* @param {number} id
*/
export function clearTimeout(id) {
inflightTimeouts.delete(id);
}

/**
*
* @param {number} id
*/
export function clearInterval(id) {
inflightTimeouts.delete(id);
}

/**
*
* @param {Object} ev
Expand Down
2 changes: 1 addition & 1 deletion rusty-workers-runtime/src/interface.rs
Expand Up @@ -16,7 +16,7 @@ pub enum SyncCall {

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum AsyncCall {
Ping,
SetTimeout(u64),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down
10 changes: 9 additions & 1 deletion rusty-workers-runtime/src/io.rs
Expand Up @@ -5,6 +5,8 @@ use slab::Slab;
use serde::{Serialize, Deserialize};
use anyhow::Result;
use crate::interface::AsyncCall;
use std::time::Duration;
use serde_json::json;

pub struct IoWaiter {
remaining_budget: u32,
Expand Down Expand Up @@ -126,5 +128,11 @@ impl IoResponseHandle {
}

async fn handle_task(task: AsyncCall) -> Result<String> {
Ok("42".into())
match task {
AsyncCall::SetTimeout(n) => {
let dur = Duration::from_millis(n);
tokio::time::sleep(dur).await;
Ok("null".into())
}
}
}

0 comments on commit 55452c6

Please sign in to comment.