Skip to content

Instantly share code, notes, and snippets.

@OrionNebula
Created April 24, 2017 03:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save OrionNebula/bd2d4339497a2c05e599d7d24038d290 to your computer and use it in GitHub Desktop.
Save OrionNebula/bd2d4339497a2c05e599d7d24038d290 to your computer and use it in GitHub Desktop.
Co-routines in TypeScript
export abstract class BlockingAction {
type: string;
abstract setup(iter: IterableIterator<BlockingAction>): void;
handleNext(iter: IterableIterator<BlockingAction>): void {
let n = iter.next();
if(n.done)
return;
n.value.setup(iter);
};
public static startCoroutine(func: () => IterableIterator<BlockingAction>): void {
let iter = func();
let n = iter.next();
if(n.done)
return;
n.value.setup(iter);
}
}
export class Wait extends BlockingAction {
wait: number;
constructor(timeout : number) {
super();
this.wait = timeout;
}
setup(iter: IterableIterator<BlockingAction>) : void {
let t = this;
setTimeout(function(){
t.handleNext(iter);
}, this.wait);
}
}
import { BlockingAction, Wait } from './BlockingAction';
function* coroutine() : IterableIterator<BlockingAction> {
let time = new Date().getTime();
console.log('Time to wait for 1 second.');
yield new Wait(1000);
console.log('This was a blocking call!');
console.log('The time taken was: ' + (new Date().getTime() - time));
}
BlockingAction.startCoroutine(coroutine);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment