Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions src/services/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ use stdweb::Value;
use html::Context;
use super::{Task, to_ms};

pub struct IntervalHandle {
interval_id: Option<Value>,
}
pub struct IntervalHandle(Option<Value>);

pub trait IntervalService<MSG> {
fn interval<F>(&mut self, duration: Duration, converter: F) -> IntervalHandle
Expand All @@ -24,27 +22,28 @@ impl<MSG: 'static> IntervalService<MSG> for Context<MSG> {
tx.send(msg);
};
let ms = to_ms(duration);
let id = js! {
let handle = js! {
var callback = @{callback};
let action = function() {
callback();
};
let delay = @{ms};
return setInterval(action, delay);
return {
interval_id: setInterval(action, delay),
callback,
};
};
IntervalHandle {
interval_id: Some(id),
}
IntervalHandle(Some(handle))
}
}

impl Task for IntervalHandle {
fn cancel(&mut self) {
let interval_id = self.interval_id.take().expect("tried to cancel interval twice");
let handle = self.0.take().expect("tried to cancel interval twice");
js! {
// TODO Drop the callback to prevent memory leak
var id = @{interval_id};
clearInterval(id);
var handle = @{handle};
clearInterval(handle.interval_id);
handle.callback.drop();
}
}
}
23 changes: 11 additions & 12 deletions src/services/timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ use stdweb::Value;
use html::Context;
use super::{Task, to_ms};

pub struct TimeoutHandle {
timeout_id: Option<Value>,
}
pub struct TimeoutHandle(Option<Value>);

pub trait TimeoutService<MSG> {
fn timeout<F>(&mut self, duration: Duration, converter: F) -> TimeoutHandle
Expand All @@ -24,28 +22,29 @@ impl<MSG: 'static> TimeoutService<MSG> for Context<MSG> {
tx.send(msg);
};
let ms = to_ms(duration);
let id = js! {
let handle = js! {
var callback = @{callback};
let action = function() {
callback();
callback.drop();
};
let delay = @{ms};
return setTimeout(action, delay);
return {
timeout_id: setTimeout(action, delay),
callback,
};
};
TimeoutHandle {
timeout_id: Some(id),
}
TimeoutHandle(Some(handle))
}
}

impl Task for TimeoutHandle {
fn cancel(&mut self) {
let timeout_id = self.timeout_id.take().expect("tried to cancel timeout twice");
let handle = self.0.take().expect("tried to cancel timeout twice");
js! {
// TODO Drop the callback to prevent memory leak
var id = @{timeout_id};
clearTimeout(id);
var handle = @{handle};
clearTimeout(handle.timeout_id);
handle.callback.drop();
}
}
}