javascript - Superfluous delay with hardcoded resolve time
问题描述
I've tried to count request - response time programmatically, and ended up with this code:
function fakeRequest(wait) {
return new Promise(resolve => {
setTimeout(() => resolve(wait), wait);
});
}
function calculateTime(fn, params) {
const startTime = new Date().getTime();
fn(...params)
.then(response => {
const endTime = new Date().getTime();
const requestTime = endTime - startTime;
console.log(`
Request should take ${response} ms
Request took ${requestTime} ms
`);
});
}
calculateTime(fakeRequest, [2000]);
In this example, we have hardcoded resolve time (2000 milliseconds), and in my understanding, the final result should be the same - 2 seconds. But when I run this code on my machine, it gives me different results between 2000ms and 2003ms.
I'm trying to figure out, where these 3 milliseconds come from:
The reason is the execution time of
new Date().getTime()
. (but if so, why do we get different results between 2000 and 2003, why it's not the same on every execution?).The reason is an asynchronous nature of the request, even though it has hardcoded resolve time.
Something else.
I'd like to hear your thoughts and find a way to get a real time of response (2 seconds in this case).
解决方案
虽然 FelixsetTimeout
无法保证确切的回调时间是正确的,但您的代码有一些注意事项。您没有尽可能早地计算结束时间(在解决之后)。我的测试稍微接近下面的所需时间。我的观点是,即使你的 setTimeout是准确的,我也不认为你的日志是正确的。
var closeEnd
function fakeRequest(wait) {
return new Promise(resolve => {
setTimeout(() => {
closeEnd = performance.now()
resolve(wait)
}, wait);
})
}
function calculateTime(fn, params) {
const startTime = performance.now()
console.log(startTime)
fn(...params)
.then(response => {
const requestTime = closeEnd - startTime;
console.log(`
Request should take ${response} ms
Request took ${requestTime} ms
`);
});
}
calculateTime(fakeRequest, [2000]);
推荐阅读
- angular - 使用 rxjs 更改成员名称
- php - 我想更改 php 分机。到 html 分机。并禁用对 php ext 的直接访问
- php - 为什么当我使用初始化方法的类型指示参数时它会返回错误?
- elasticsearch - 如何分离 Elastic APM 代理?
- angular - 如何在firebase实时数据库中设置数据值?
- c# - 如何使用社交分享插件向 whatsapp 群组发送短信
- python - 使用 PyQt 的 QLineEdit 滚动条
- google-cloud-dataflow - 为什么 mongoio Reshuffle 不能在数据流上工作
- python - 从 RESTAPI url 在 python 中下载大型 zip 文件只会下载 1KB 的文件
- c# - 如何使用 MongoDB 驱动程序在 mongodb 中“选择 WHERE”