Skip to content

Instantly share code, notes, and snippets.

@nobishino
Created July 23, 2020 07:57
Show Gist options
  • Save nobishino/d7a0c0ea9a7db006eeae84701cf0e053 to your computer and use it in GitHub Desktop.
Save nobishino/d7a0c0ea9a7db006eeae84701cf0e053 to your computer and use it in GitHub Desktop.
一定回数実行するかボタンがクリックされるとキャンセルされるlotteryの例1
// timer機能と、定期的に実行される操作が混ざっている
class AutoLottery {
constructor(action, interval) {
this.action = action;
this.interval = interval;
this.count = 0;
}
start() {
const execute = () => {
this.action();
this.count++;
this.timeoutId = setTimeout(execute, this.interval);
if (this.count > 3) {
this.stop();
console.log("lottery stopped");
}
}
this.timeoutId = setTimeout(execute, this.interval);
console.log("lottery started!");
}
stop() {
if (!this.timeoutId) return;
console.log("lottery stop!");
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
}
class Button {
constructor(onClick) {
this.onClick = onClick;
}
click() {
console.log("clicked!");
this.onClick();
}
}
let x = 0;
const action = () => {
console.log(`lottery ${x++}`);
}
const lottery = new AutoLottery(action, 1000);
const button = new Button(() => { lottery.stop() });
lottery.start();
setTimeout(() => { button.click() }, 3000); // simulate click after 3sec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment