Skip to content

Instantly share code, notes, and snippets.

@fujidig
Created September 7, 2011 08:22
Show Gist options
  • Save fujidig/1200041 to your computer and use it in GitHub Desktop.
Save fujidig/1200041 to your computer and use it in GitHub Desktop.
function Trampoline(func) {
this.task = new Task(func);
}
Trampoline.prototype.step = function() {
if (!this.task) return;
this.task = this.task.cont();
if (this.task) this.task.nextStep = this.step.bind(this);
};
Trampoline.prototype.cancel = function() {
if (this.task && this.task.canceler) {
this.task.canceler();
}
this.task = null;
}
function Task(cont) {
this.cont = cont;
this.nextStep = null;
this.canceler = null;
}
Task.prototype.getCallback = function() {
var self = this;
return function() { self.nextStep() };
};
function wait(cont, sec) {
var task = new Task(cont);
var timerId = setTimeout(task.getCallback(), sec * 1000);
task.canceler = function() { clearTimeout(timerId) };
return task;
}
function f1() {
console.log(1);
return wait(f2, 1);
}
function f2() {
console.log(2);
return wait(f3, 1);
}
function f3() {
console.log(3);
return null;
}
var trampoline = new Trampoline(f1);
trampoline.step();
setTimeout(function () {
console.log("cancel!");
trampoline.cancel();
}, 1500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment