Skip to content
Advertisement

Javascript Time. Add +1 to current time

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

<div id="output"></div>
<script>
    const output = document.querySelector("#output");
    let time = "12:48:39"
    let seconds = 0;

    function timer() {
        seconds++;
        let hours = Math.floor(seconds / 3600);
        // Get minutes
        let minutes = Math.floor((seconds - hours * 3600) / 60);
        // Get seconds
        let secs = Math.floor(seconds % 60);

        if (hours < 10) {
            hours = `0${hours}`;
        }
        if (minutes < 10) {
            minutes = `0${minutes}`;
        }
        if (secs < 10) {
            secs = `0${secs}`;
        }
        return `${hours}:${minutes}:${secs}`;
    }
    setInterval(() => {
        output.innerHTML = parseInt(time + timer())
    }, 1000)
</script>

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.

<div id="output"></div>
<script>
    const output = document.querySelector("#output");
    let time = "12:48:39"
    let a = time.split(':');
    let seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); ;
    let ti = "";
    function timer() {
        seconds++;
        let hours = Math.floor(seconds / 3600);
        // Get minutes
        let minutes = Math.floor((seconds - hours * 3600) / 60);
        // Get seconds
        let secs = Math.floor(seconds % 60);
        
        if (hours < 10) {
            hours = `0${hours}`;
        }
        if (minutes < 10) {
            minutes = `0${minutes}`;
        }
        if (secs < 10) {
            secs = `0${secs}`;
        }
        ti = `${hours}:${minutes}:${secs}`;
        return ti;
    }
    setInterval(() => {
        output.innerHTML = timer();
    }, 1000)
</script>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement