gpt4 book ai didi

javascript - 计算两个函数调用之间耗时

转载 作者:行者123 更新时间:2023-12-03 06:23:37 24 4
gpt4 key购买 nike

我一直在尝试计算两个函数调用之间耗时。我写了一个这样的示例代码

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

最佳答案

问题是您的变量 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>';
}

关于javascript - 计算两个函数调用之间耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38750609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com