+ 1
Incrementing with setInterval
I'm trying to work on a stopwatch code and it has went really well so far. I've managed to get an update to the cinsole log every second so far and the code is mostly complete. However I've hit a block in not being being able to update the displayed time when using the increment operator (++). I'm also having problems with updating the html display using innerHTML, as when. It commented out it state that there is a null error. Any help and advise on these issues would be great. I've attached my code but unsure if it can be seen s it's currently private due to me not wanting to realise it without it being finished, if that's the case let me know. https://code.sololearn.com/WvcBBt3eR34U/?ref=app
8 Answers
+ 3
Each button is missing the quotes for onclick attributes, onclick = "",
Button with the Id="reset" does not have an onclick,
In the function updateTimer() : there is a typo, seonds = 0 should be seconds = 0
+ 3
Excuse me I'm having more trouble thinking of how to explain this, than finding the issues.
Remove the parameters from the updateTimer function declaration and reference the global variables directly within the function.
function updateTimer() {
...
}
}
}
time = `${hours}:${minutes}:${seconds}.${milliseconds}`;
console.log(time)
stopwatch.innerHTML = time;
}
+ 2
This isn't the complete solution. But I notice that your h2 class is "timerClock", but in JS its you're targeting an Id
stopwatch= document.getElementById
You can correct that with stopwatch = document.querySelector(".timerClock")
+ 2
You have too many errors, so replace some of your code with this one and find the differences yourself:
let milliseconds = 0
let seconds = 0
let minutes = 0
let hours = 0
//onload = ()=> stopwatch = document.getElementById("timerClock")
// updates variables
function updateTimer() {
milliseconds++
if (milliseconds >= 100) {
seconds++
milliseconds = 0
if (seconds >= 60) {
minutes++
seconds = 0
if (minutes >= 60) {
hours++
minutes = 0
}
}
}
//stopwatch
timerClock
.innerHTML = `${hours}:${minutes}:${seconds}.${milliseconds}`
}
// starts the timer
function start() {
interval = setInterval(updateTimer, 10)
}
My stopwatch... 😎:
https://code.sololearn.com/WR4UvCZ031Ml/?ref=app
+ 2
If you have made the proper corrections, now, you should at least have a functional stop watch with working start and stop buttons. If you find anything helpful please like or if you find anything confusing, please ask more questions. - Happy Coding!
+ 2
Callum Stewart You're welcome! No worries, many of us are here to learn, share knowledge, and experiences. And yes, simple typing mistakes can sometimes feel like the final boss.
+ 1
That was definitely meant to be an id target, not a class, I've updated the code with get elementbyid now, thank you.
0
Thank you so much for your help. I obviously have a few things to go back over and have a look at, mainly my typing skills xD.