Reputation: 355
I am trying to show a timer that rises each second using setInterval.
The variable seems to reset itself on each loop though; the result being that the display on the HTML page doesn't change.
I've moved the variables outside of the function, but this doesn't work. Not really sure where to go from here.
this.intervalFour = setInterval(() => this.totalTime(this.secs, this.restSecs), 1000);
totalTime(seconds, rests) {
var fullTime = seconds * 8 + rests * 7;
fullTime--;
var secCounter: any = 0;
var minCounter: any = 0;
secCounter++;
if (secCounter < 10) {
secCounter = "0" + secCounter;
}
if (minCounter < 10) {
minCounter = "0" + minCounter;
}
if (secCounter == 60) {
secCounter = 0;
minCounter++;
}
if (fullTime = 0) {
clearInterval(this.intervalFour);
}
this.m.innerHTML = minCounter;
this.s.innerHTML = secCounter;
console.log(secCounter, minCounter, "test");
}
I know this is a silly thing to get stuck on, but I can't find the solution to get the secCounter to rise by one on each loop.
Upvotes: 0
Views: 308
Reputation: 7949
You can try the following approach.
Though I don't have certain value therefore I commented that code, you can uncomment that code as per your need:
<script type="text/javascript">
var secs = 10;
var restSecs = 10;
var secCounter = 0;
var minCounter = 0;
this.intervalFour = setInterval(() => this.totalTime(this.secs, this.restSecs), 1000);
function totalTime(seconds, rests) {
var fullTime = seconds * 8 + rests * 7;
fullTime--;
this.secCounter++;
if (this.secCounter < 10) {
this.secCounter = "0" + this.secCounter;
}
if (this.minCounter < 10) {
this.minCounter = "0" + this.minCounter;
}
if (this.secCounter == 60) {
this.secCounter = 0;
this.minCounter++;
}
// if (fullTime = 0) {
// clearInterval(this.intervalFour);
// }
console.log("this.minCounter" , this.minCounter);
console.log("this.secCounter" , this.secCounter);
// this.m.innerHTML = this.minCounter;
// this.s.innerHTML = this.secCounter;
console.log(this.secCounter, this.minCounter, "test");
}
In this solution, the seconds gets perfectly increasing on every second.
Upvotes: 1
Reputation: 1
In case you are looking to show some kind of timer, this may help.
const displayTime = (ticks) => {
const seconds = parseInt(ticks % 60);
let minute = parseInt(ticks / 60);
const hour = parseInt(minute / 60);
if (hour > 0) {
minute = parseInt(minute % 60);
}
console.log([hour, minute, seconds].join(':'));
};
const tick = 0;
setInterval(()=> displayTime(tick++), 1000);
Upvotes: 0
Reputation: 68
I'm not sure it is right, because there is no full code in here, but i think 'this' keyword in setInterval callback function is a problem.
'this' in setInterval callback is binded to global 'this', in this case Window object.
so, you need to specify 'this' object like this.
const self = this;
self.secs = initSecs;
self.restSecs = initRestSecs;
self.totalTime = function totalTime() { ... };
setInterval(() => self.totalTime(self.secs, self.restSecs), 1000);
Upvotes: 0