Sorry for the vague question, but wasn't sure how to phrase it.
I'm creating a timer (with a progress bar, that goes from 100% to 0), and I want to add something like a 'onStop' function for the user to use. This function would be called after the timer reaches 0. How would I add it to my class?
Current code:
"use strict";
const progressBar = {
// Default config, set to countdown starting at 3 minutes
config: {
// Define time in seconds
time: 180, // 3 minutes
// Wrapper
wrapper: '',
// New element that will be the actual progress bar inside the wrapper
bar: ''
},
//onStop: function() { console.log('triggered'); }, // custom function
onStart: function() {}, // custom function
bind: function(el) {
this.createBar(el);
},
createBar: function(el) {
const wrapper = document.getElementById(el);
const bar = document.createElement("div");
this.config.bar = bar;
this.config.bar.id = "progressbar-inside";
this.config.bar.style.width = '100%';
this.config.bar.style.height = '100%';
wrapper.appendChild(bar);
},
start: function() {
//const percentage = 0.55
const percentage = 100 / this.config.time;
const time = this.config.time;
progressBar.countDown(percentage, '100', time-1);
},
countDown: function(percentage, width, time) {
const new_time = time-1;
const new_width = width - percentage;
this.config.bar.style.width = new_width + '%'
console.log(time);
if (time === 0) {
progressBar.onStop();
return;
}
setTimeout(function() {
progressBar.countDown(percentage, new_width, new_time)
}, 1000);
}
}
Someone could use this like so:
progressBar.bind('progressbar');
progressBar.config.time = 25;
progressBar.start();
What should I add if I want to allow the end user to do:
progressBar.onStop(function() {
// Timer finished! Do stuff here
});
Collect the stop handlers inside of an array:
stopHandlers: [],
Then when onStop
gets called just push the function to that array:
onStop(fn) { this.stopHandlers.push(fn); },
Then to trigger them (inside of some method):
this.stopHandlers.forEach(fn => fn());