![](/img/trans.png)
[英]How do I loop images in a div downwards infinitely using javascript?
[英]How do I test the time images take to load using a javascript loop
我正在尝试进行一些测试,以查看不同的图像需要多长时间才能返回到我的浏览器。 我正在使用JavaScript进行循环。 但是,循环似乎在加载第一个图像之前运行,并且返回没有给出准确的答案。 下面是我的代码:
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
我尝试了不同的方法来尝试使循环仅在加载每个映像之后才运行,但没有成功。 有任何想法吗? 谢谢!
您需要将radius
和startTime
放在闭合startTime
中,否则您将始终引用相同的变量:
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.