Javascript 为什么performance.now()和Chrome';s的性能工具显示不同的结果?

Javascript 为什么performance.now()和Chrome';s的性能工具显示不同的结果?,javascript,google-chrome,Javascript,Google Chrome,我创建了一段快速的代码来测试这一点。我将此脚本包含在页面中并刷新了浏览器: const startTime = performance.now(); const img = new Image(); img.src = 'https://www.google.co.uk/images/branding/googleg/1x/googleg_standard_color_128dp.png?' + Math.random(); const endTime = performance.now();

我创建了一段快速的代码来测试这一点。我将此脚本包含在页面中并刷新了浏览器:

const startTime = performance.now();
const img = new Image();
img.src = 'https://www.google.co.uk/images/branding/googleg/1x/googleg_standard_color_128dp.png?' + Math.random();
const endTime = performance.now();
const downloadTime = endTime - startTime;
console.log(downloadTime);
脚本将
endTime
报告为
0.19000000000005457
endTime
值是
DOMHighResTimestamp
的一个实例

但是chrome开发者工具报告说它花了81毫秒。这对我的问题来说是相当大的不同。如果只花了81毫秒,为什么我的脚本报告为190毫秒?还是我遗漏了一些明显的东西

编辑

感谢Josh的回答,他指出它需要在
load
处理程序中。我的错。但遗憾的是,这些价值观仍然不一致


还有,为什么投票被否决?这是一个合理的问题。我需要知道最后一个细节,因为一个非常具体的原因,下载一个特定的图像需要多长时间。

记住JavaScript是单线程的——任何网络代码都是通过事件处理程序异步进行的。任何可以自上而下读取的代码都或多或少是瞬间发生的(除非DOM/CSS滥用严重,或者大量CPU限制的代码)

看起来你想知道下载图片花了多长时间?观察图像上的
load
事件

const startTime=performance.now();
const img=新图像();
img.addEventListener('load',()=>{
const endTime=performance.now();
const downloadTime=endTime-startTime;
console.log(下载时间);
});

img.src=https://www.google.co.uk/images/branding/googleg/1x/googleg_standard_color_128dp.png?“+Math.random()
您对它进行了多次测试吗?也许是缓存了什么的是的我做了。正如我添加的
Math.random()一样,它不是缓存
到图像URL的末尾,以确保浏览器不会缓存。哦,很好,我没有在末尾注意到它。与
Network
选项卡上的
DevTools
显示的请求属性相关的
const downloadTime=endTime-startTime
?可能谷歌指示的时间只涉及图像的检索,你的脚本还需要创建对象和注入DOM?谢谢Josh。在我的原始代码中,endTime并没有等待下载完成。你的解决方案有效。问题是这些值仍然处于关闭状态。我认为你是对的,尽管其他进程导致它显示不同的时间。很好的解释和示例,但结果仍然有点奇怪,我第一次运行时得到大约150到250,再次运行时只有60到80。当使用清理缓存(CTRL+F5)进行刷新时,它会再次使用大值(Firefox)进行刷新。有些东西似乎被放进了完美的缓存!这篇报道的时间完全相同。但它没有IE支持。我会弄明白的。
const downloadTime = endTime - startTime;