Time duration Counter format (00:00:00) for stopwatch , media recording etc..


 

 This piece of code could be used to show time counting like when we recording something with media recording and want to show a time counter to indicate how much recording has been recorded in hours, minute and second, in format (00:00:00) time duration .

    

function getTimeCount() {
    var startDateTime = new Date();
    var startStamp = startDateTime.getTime();
    var newDate = new Date();
    var newStamp = newDate.getTime();
    return (cb=> {
        var formatTimeCounter = (val=> {
         return val = val < 10 ? `0${val}` : val;
        }
        newDate = new Date();
        newStamp = newDate.getTime();
        var diff = Math.round((newStamp - startStamp) / 1000);
        var d = Math.floor(diff / (24 * 60 * 60)); 
        diff = diff - (d * 24 * 60 * 60);
        var h = Math.floor(diff / (60 * 60));
        diff = diff - (h * 60 * 60);
        var m = Math.floor(diff / (60));
        diff = diff - (m * 60);
        var s = diff;
        var tStr =`${formatTimeCounter(h)}:${formatTimeCounter(m)}:${formatTimeCounter(s)}`
        cb(tStr);
    }
}



var recordCount = getTimeCount();
var id  = setInterval(() => {
  recordCount((time=> {
        document.getElementById("timetest").value = time;
        //console.log(time);
  });
}, 1000)

getTimeCount method return a function that return a time stamp in format hh:mm:ss , so we using 

setInterval method to get updated time from getTimeCount  every 1 sec and the print the time in console or whatever you want to display it,   

to stop this timer clear the time interval 

clearInterval(id);

comment if you have better code or suggestion.




Comments