2016-08-03 190 views
0

我一直在試圖計算兩次函數調用之間的時間間隔。 我寫了一個示例代碼這樣計算兩次函數之間的時間間隔呼叫

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>'; 
} 

我的輸出是

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 

和我的預期產出是這樣的(任意時間在這個例子中)

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

等。 。

我做錯了什麼?

代碼例如:http://codepen.io/gpincheiraa/pen/oLPOVY

回答

1

的問題是,你的可變timeElapsed被用來表示當前時間和函數調用之間的時間。我建議把它分成兩個變量:

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>'; 
}