0

我正在尝试执行一些测试,以查看不同的图像需要多长时间才能返回到我的浏览器。我正在使用 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 

我尝试了不同的方法来尝试仅在每个图像加载后才运行循环而没有任何成功。有任何想法吗?谢谢!

4

1 回答 1

0

您需要将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";
}
于 2013-04-01T15:05:05.400 回答