我想衡量RTT对服务器的持续时间...... 这是问题所在,当我完成以下工作时,它可以完美地运作:
var start = new Date();
var startTime=start.getMilliseconds();
document.write('<img src="http://mysite.com/myfile.gif" onload="getEndTime()">');
function getEndTime()
{
var stop= new Date();
var t=stop.getMilliseconds()-startTime;
console.log(t);
}
但是如果我想将t存储在变量中并将其打印出函数,那么大部分时间都不起作用!
例如:
var start = new Date();
var startTime=start.getMilliseconds();
document.write('<img src="http://mysite.com/myfile.gif" width="1" height="1" onload="getEndTime()">');
var rtt;
function getEndTime()
{
var stop= new Date();
var t=stop.getMilliseconds()-startTime;
rtt=t;
}
console.log(rtt);
rtt大部分时间都是0 !!有人可以帮忙吗?真令人沮丧!....
答案 0 :(得分:0)
你永远不会调用getEndTime
(我可以看到),所以如何设置rtt
(在调用console.log时)。
也许在页面上添加一个按钮,或在您分配console.log
后添加rtt
?
页面步骤,正如我看到的那样:
var begin = new Date,
rtt = [],
imgs = [
'http://myserver.com/foo.gif',
'http://myserver.com/bar.gif'
// etc.
];
function getEndTime(){
var end = new Date;
var delta = end.getMilliseconds() - begin.getMilliseconds();
console.log('image loaded in ' + delta + 'ms');
rtt.push(delta);
}
function dumpSummary(){
// based on the number of entried in our rtt array, we can determine
// if all the images have been loaded. if not, re-call this function (with
// a delay until we reach it.
if (rtt.length == imgs.length){
console.log('All images have loaded. Their times are:');
for (var r = 0; r < rtt.length; r++){
console.log(r + '. ' + rtt[r]);
}
}else{
console.log('waiting on more images...');
// not enough entries, try again later
setTimeout(dumpSummary,1000);
}
}
// begin polling for the "finish line"
dumpSummary();
// output the images one-by-one
console.log('beginning');
for (var i = 0; i < imgs.length; i++)
document.write('<img src="' + imgs[i] + '" width="1" height="1" alt="" onload="getEndTime();" />');