简体   繁体   中英

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

I am trying to perform some tests to see how long different images take to return to my browser. I am using a javascript for loop. However, The loop seems to run before the first image is loaded and the return does not give an accurate answer. Below is my code:

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; 
}

As a result, I get:

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 

I tried different methods of trying to get the loop to run only after each image is loaded without any success. Any ideas? Thanks!

You need to put the radius and the startTime in a closure, otherwise you will always refer to the same variable:

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM