Created
July 23, 2020 07:57
-
-
Save nobishino/d7a0c0ea9a7db006eeae84701cf0e053 to your computer and use it in GitHub Desktop.
一定回数実行するかボタンがクリックされるとキャンセルされるlotteryの例1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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