Calc the time elapsed between 2 functions call

I've been trying to calculate the time elapsed between 2 functions call. I wrote a sample code like this

var timeElapsed = Date.now(),
    div = document.getElementById("hour");

//routine
setInterval(function(){
    setTimeout(fn1, 1000);
    setTimeout(fn2, 1000);
},2000)

function formatHour(date){
    var hours = ('0' + date.getHours()).slice(-2),
        minutes = ('0' + date.getMinutes()).slice(-2),
        seconds = ('0' + date.getSeconds()).slice(-2),
        millis = ('00' + date.getMilliseconds()).slice(-3);

    return ([hours,minutes,seconds].join(':')) + ',' + millis;
}

function fn1(){
    timeElapsed = Date.now() - timeElapsed;
    div.innerHTML += formatHour(new Date(timeElapsed)) + ' --> '
}
function fn2(){
    timeElapsed = Date.now() - timeElapsed;
    div.innerHTML += formatHour(new Date(timeElapsed)) + '</br>';
}

my output it's

22:00:03,001 --> 13:52:42,115
22:00:05,000 --> 13:52:42,115
22:00:07,000 --> 13:52:42,115
22:00:10,980 --> 13:52:42,115
22:00:12,981 --> 13:52:42,115

and my expected outputs it's like this (with arbitrary time for this example)

00:00:00,000 --> 00:00:05,212
00:00:05,212 --> 00:00:08,450
00:00:08,450 --> 00:00:12,999

etc...

What i doing wrong?

code example: http://codepen.io/gpincheiraa/pen/oLPOVY

Upvotes: 0

Views: 113

Answers (1)

Eric Dobbs
Eric Dobbs

Reputation: 237

The problem is that your variable timeElapsed is being used to represent both the current time and the time between function calls. I would recommend breaking it into two variables:

var startTime = Date.now(),
    div = document.getElementById("hour");

//routine
setInterval(function(){
    setTimeout(fn1, 1000);
    setTimeout(fn2, 1000);
},2000)

function formatHour(date){
    var hours = ('0' + date.getHours()).slice(-2),
        minutes = ('0' + date.getMinutes()).slice(-2),
        seconds = ('0' + date.getSeconds()).slice(-2),
        millis = ('00' + date.getMilliseconds()).slice(-3);

    return ([hours,minutes,seconds].join(':')) + ',' + millis;
}

function fn1(){
    var timeElapsed = Date.now() - startTime;
    div.innerHTML += formatHour(new Date(timeElapsed)) + ' --> '
}
function fn2(){
    var timeElapsed = Date.now() - startTime;
    div.innerHTML += formatHour(new Date(timeElapsed)) + '</br>';
}

Upvotes: 1

Related Questions