Skip to content

Instantly share code, notes, and snippets.

@jeffersontpadua
Created October 25, 2019 13:12
Show Gist options
  • Save jeffersontpadua/159b8f9064f53ab672bb3f18b183357a to your computer and use it in GitHub Desktop.
Save jeffersontpadua/159b8f9064f53ab672bb3f18b183357a to your computer and use it in GitHub Desktop.
Count to a certain number
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