I tried to make kind of object to work with my timer. The thing is when I have only bare functions (which are not in object) it is working. But When I put it inside object it doesnt work.
With this code I see only 00:01
When I used only the functions themselves it was working ok, I would like to have them in object cos I will have more functions in my code.
Thanks for help
$(document).ready(function() {
var Timer = {
TimerID: null,
elapsed: 0,
changeTimer: function() {
this.TimerID = setInterval(this.timerTick(), 1000);
},
timerTick: function() {
this.elapsed++;
var minutes = Math.floor(this.elapsed / 60);
var seconds = this.elapsed - (minutes * 60);
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('.timer-html').text(minutes + ":" + seconds);
},
stopTimer: function() {
clearInterval(this.TimerID);
}
};
console.log(Timer);
$(".timer").click(Timer.changeTimer());
$(".stop-timer").click(Timer.stopTimer());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:;" class="timer">start clock</a>
<a href="javascript:;" class="stop-timer">stop clock</a>
<h1 class="timer-html">00:00</h1>
setInterval(this.timerTick(), 1000);Is wrong, it is executingtimerTickonce then passing the return value, which is undefined, into setInterval. Instead either passtimerTickin directly (without executing it) or wrap it in an annon function. Also be aware of context changes when using setInterval/settimeout. Either:setInterval(() => this.timerTick(), 1000);orsetInterval(this.timerTick, 1000);