Hi I want my timer to continue from the current time each second. Keeping the same time format. I just added a simple code to check.
Code
JavaScript
x
30
30
1
<div id="output"></div>
2
<script>
3
const output = document.querySelector("#output");
4
let time = "12:48:39"
5
let seconds = 0;
6
7
function timer() {
8
seconds++;
9
let hours = Math.floor(seconds / 3600);
10
// Get minutes
11
let minutes = Math.floor((seconds - hours * 3600) / 60);
12
// Get seconds
13
let secs = Math.floor(seconds % 60);
14
15
if (hours < 10) {
16
hours = `0${hours}`;
17
}
18
if (minutes < 10) {
19
minutes = `0${minutes}`;
20
}
21
if (secs < 10) {
22
secs = `0${secs}`;
23
}
24
return `${hours}:${minutes}:${secs}`;
25
}
26
setInterval(() => {
27
output.innerHTML = parseInt(time + timer())
28
}, 1000)
29
</script>
30
Advertisement
Answer
Here is the working solution.
You had to split your string that represents time, so you can count the amount of seconds that you actually had.
Note: I’ve used this as help for transitioning from HH:MM:SS to numbers.
And, in the end, you just need to get the timer()
string, there is no need to write both time and the return element of timer function.
JavaScript
1
31
31
1
<div id="output"></div>
2
<script>
3
const output = document.querySelector("#output");
4
let time = "12:48:39"
5
let a = time.split(':');
6
let seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); ;
7
let ti = "";
8
function timer() {
9
seconds++;
10
let hours = Math.floor(seconds / 3600);
11
// Get minutes
12
let minutes = Math.floor((seconds - hours * 3600) / 60);
13
// Get seconds
14
let secs = Math.floor(seconds % 60);
15
16
if (hours < 10) {
17
hours = `0${hours}`;
18
}
19
if (minutes < 10) {
20
minutes = `0${minutes}`;
21
}
22
if (secs < 10) {
23
secs = `0${secs}`;
24
}
25
ti = `${hours}:${minutes}:${secs}`;
26
return ti;
27
}
28
setInterval(() => {
29
output.innerHTML = timer();
30
}, 1000)
31
</script>