UNPKG

crono-pice

Version:

Crono that receives a DOM element and inserts 3 buttons to start, stop and reset the Crono

85 lines (69 loc) 2.1 kB
class CronoPice { #tiempoInicio = 0; #tiempoFinal = 0; segundos = 0; idIntervalo; startButton = document.createElement('button'); stopButton = document.createElement('button'); resetButton = document.createElement('button'); timeOutput = document.createElement('h3'); constructor (output) { this.output = output; this.generateHTML(); this.addHTMLToDOM(); } generateHTML () { this.startButton.innerText = 'Start'; this.stopButton.innerText = 'Stop'; this.resetButton.innerText = 'Reset'; this.timeOutput.innerText = '0seg.'; this.startButton.onclick = () => this.start(); this.stopButton.onclick = () => this.stop(); this.resetButton.onclick = () => this.reset(); } addHTMLToDOM () { this.output.append(this.timeOutput, this.startButton, this.resetButton, this.stopButton) } start () { if (this.#tiempoInicio) { console.error('Ya está en marcha.') return; } this.idIntervalo = setInterval(() => { this.segundos += 0.01; this.timeOutput.innerText = this.segundos.toFixed(2) + 'seg.'; }, 10); this.#tiempoInicio = Date.now(); } stop () { if (!this.#tiempoInicio) { console.error('Antes tienes que ponerlo en marcha.'); return; } if (this.#tiempoFinal) { console.error('Ya ha sido parado'); return; } clearInterval(this.idIntervalo); this.#tiempoFinal = Date.now(); this.showTime(); } reset () { if (!this.#tiempoInicio) { return console.error('No ha sido ni siquiera iniciado.'); } if (!this.#tiempoFinal) { return console.error('Antes tienes que pararlo.') } this.#tiempoInicio = 0; this.#tiempoFinal = 0; this.showTime(); } showTime () { const diff = this.#tiempoFinal - this.#tiempoInicio; const diffInSeconds = (diff / 1000).toFixed(2) + 'seg.' this.timeOutput.innerText = diffInSeconds; return diffInSeconds; } } export default CronoPice;