Skip to content

Instantly share code, notes, and snippets.

@nobishino
Created July 23, 2020 08:05
Show Gist options
  • Save nobishino/f99cef386c425a9a40c23189de677703 to your computer and use it in GitHub Desktop.
Save nobishino/f99cef386c425a9a40c23189de677703 to your computer and use it in GitHub Desktop.
// timerにexecutorを渡す例
// timerは定期実行と定期実行の終了に責任を持つ
// 実行される処理と処理を終了すべきかどうかの判断はexecutorが持つ
class Timer {
constructor(executor, interval) {
this.executor = executor;
this.interval = interval;
}
start() {
const execute = () => {
this.timeoutId = setTimeout(execute, this.interval);
this.executor.do();
if (this.executor.shouldTerminate()) {
this.stop();
}
}
this.timeoutId = setTimeout(execute, this.interval);
console.log("timer started!");
}
stop() {
if (!this.timeoutId) return;
console.log("timer stop!");
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
}
class Lottery {
constructor(numbers) {
this.numbers = numbers;
this.index = 0;
}
do() {
if (this.index >= this.numbers.length) return;
console.log(`lottery #${this.index} returns ${this.numbers[this.index++]}`);
}
shouldTerminate() {
return (this.index >= this.numbers.length);
}
}
class Button {
constructor(onClick) {
this.onClick = onClick;
}
click() {
console.log("clicked!");
this.onClick();
}
}
const executor = new Lottery([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9]);
const timer = new Timer(executor, 1000);
const button = new Button(() => { timer.stop() });
timer.start();
setTimeout(() => { button.click() }, 10000); // simulate click after 10sec
// 実行結果
// timer started!
// lottery #0 returns 3
// lottery #1 returns 1
// lottery #2 returns 4
// lottery #3 returns 1
// lottery #4 returns 5
// lottery #5 returns 9
// lottery #6 returns 2
// lottery #7 returns 6
// lottery #8 returns 5
// clicked!
// timer stop!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment