首页 > 解决方案 > 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:

  1. 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?).

  2. The reason is an asynchronous nature of the request, even though it has hardcoded resolve time.

  3. 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).

标签: javascriptasynchronoustimepromise

解决方案


虽然 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]);


推荐阅读