我如何使用javascript循环测试图像加载的时间

How do I test the time images take to load using a javascript loop

本文关键字:加载 时间 图像 循环测试 何使用 javascript      更新时间:2023-09-26

我正在尝试执行一些测试,看看不同的图像需要多长时间才能返回到我的浏览器。我正在使用一个javascript for循环。然而,循环似乎在加载第一个图像之前运行,并且返回没有给出准确的答案。下面是我的代码:

for (var radius=1; radius<10; radius++)
{
var startTime = new Date().getTime();
var img = new Image();
img.onload = function() {
    var loadtime = new Date().getTime() - startTime;
    console.log("image with radius: "+radius+" took " + loadtime + "ms to load");
};

url="http://test"+radius+"test2.com";
img.src = url; 
}

结果,我得到:

image with radius: 10 took 175ms to load 
image with radius: 10 took 368ms to load 
image with radius: 10 took 463ms to load 
image with radius: 10 took 608ms to load 
image with radius: 10 took 751ms to load 
image with radius: 10 took 895ms to load 
image with radius: 10 took 1038ms to load 
image with radius: 10 took 1181ms to load 
image with radius: 10 took 1324ms to load 

我尝试了不同的方法,试图让循环只在每个图像加载后才运行,但没有成功。什么好主意吗?谢谢!

您需要将radiusstartTime变量放在闭包中,否则您将始终引用相同的变量:

function getLoadhandler(starttime, logmsg) {
    return function() {
         // get the local variables
         console.log(logmsg+": "+(starttime-Date.now()));
    };
}
for (var radius=1; radius<10; radius++) {
    var img = new Image();
    img.onload = getLoadhandler(Date.now(), "Load time of image with radius "+radius);
    img.src = "http://test"+radius+"test2.com";
}