Created
October 25, 2019 13:12
-
-
Save jeffersontpadua/159b8f9064f53ab672bb3f18b183357a to your computer and use it in GitHub Desktop.
Count to a certain number
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
const Counter = { | |
handler: null, | |
end: 5, | |
seconds: 0, | |
start: () => { | |
if (Counter.handler) { | |
clearInterval(Counter.handler); | |
Counter.seconds = 0; | |
} | |
Counter.handler = setInterval(() => { | |
Counter.seconds++; | |
Counter.listeners | |
.filter(listener => listener.type === "onTick") | |
.forEach(listener => listener.callback(Counter.seconds)); | |
if ( | |
Counter.seconds === Counter.end && | |
Counter.listeners.length !== 0 | |
) { | |
Counter.listeners | |
.filter(listener => listener.type === "onComplete") | |
.forEach(listener => listener.callback()); | |
Counter.stop(); | |
} | |
}, 1000); | |
}, | |
stop: () => { | |
if (Counter.handler) { | |
clearInterval(Counter.handler); | |
} | |
}, | |
listeners: [] | |
}; | |
// Example | |
Counter.listeners.push({ | |
type: "onComplete", | |
callback: () => console.log("Done!") | |
}); | |
Counter.listeners.push({ | |
type: "onTick", | |
callback: seconds => console.log(seconds) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment