JSFiddle - React, Tailwind, and code Playground
by TCloud
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button class="firstTimerRunBtn">First Timer Run</button>
<button class="firstTimerStopBtn">First Timer Stop</button>
<div class="firstTimerValue"> { ... } </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
JavaScript
let settingsForTimers = {
configObjectForFirstTimer: {
state: false,
now: 0,
step: 1000 // 1s
},
configObjectForSecondTimer: {
state: false,
now: 0,
step: 5000 // 5s
},
}
class MyTimer {
constructor( config ) {
this.config = config
this.timerID = 0
}
start() {
// start timer
this.config.state = true
this.count()
}
stop() {
this.config.state = false
this.count()
}
count() {
if( this.config.state == true ) {
this.timerID = setInterval( () => {
this.config.now += 1;
// show "now" in div element
$(".firstTimerValue").text( this.config.now );
}, this.config.step )
} else if( this.config.state == false ) {
clearInterval( this.timerID )
}
}
}
// test varibles for timer.
let firstTimer = new MyTimer( settingsForTimers.configObjectForFirstTimer );
let secondTimer = new MyTimer( settingsForTimers.configObjectForSecondTimer );
// events for html elements
$(".firstTimerRunBtn").click(function() {
firstTimer.start()
})
$(".firstTimerStopBtn").click(function() {
firstTimer.stop()
})