Random programming things I'd want to remember

Thursday, January 11, 2018

Timer to count up in JavaScript

Here is my implementation, nothing original or extraordinary. Putting it here for future reference.
        
        var totalSeconds = 0;
        var timer;

        function startTimer() {
            timer = setInterval(function () {
                totalSeconds++;
                var t = document.getElementById("time2"); //or other place where to display data
                t.innerHTML = displayTimer(totalSeconds);
            }, 1000); 
        }

        function stopTimer() {
            clearInterval(timer);
        }

        function displayTimer(numberOfSeconds) {
            var result = "";

            var hours = Math.floor(numberOfSeconds / 3600);
            if (hours > 0) { result += hours + " h "; }

            var minutes = Math.floor((numberOfSeconds - (hours * 3600)) / 60);
            if (minutes > 0) { result += minutes + " m "; }

            result += (numberOfSeconds % 60 + " s");

            return result;
        }

No comments: