Skip to content

Instantly share code, notes, and snippets.

@kwoncharles
Created January 7, 2019 05:34
Show Gist options
  • Save kwoncharles/dc65749f9ce1eee2be1ca85d88d041c3 to your computer and use it in GitHub Desktop.
Save kwoncharles/dc65749f9ce1eee2be1ca85d88d041c3 to your computer and use it in GitHub Desktop.
Examples from "JS 비동기 프로그래밍 이해하기[2]"
class Countdown extends EventEmitter {
constructor(seconds, superstitious) {
super();
this.seconds = seconds;
this.superstitious = !!superstitious;
}
go() {
const countdown = this;
const timeoutIds = [];
return new Promise((resolve, reject) => {
for (let i = countdown.seconds; i >= 0; i--) {
timeoutIds.push(setTimeout(() => {
if(countdown.superstitious && i === 13) {
timeoutIds.forEach(clearTimeout);
return reject(new Error('OMG'));
}
countdown.emit('tick', i);
if(i === 0) resolve();
}, (countdown.seconds - i) * 1000));
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment