延迟计算通过AJAXAJAX

2023-09-11 01:04:45 作者:我不败家你的钱给谁花

我想告诉我的网站的用户的连接速度(延迟?)。我认为它可以通过测量XMLHtt prequest对象请求和响应时间是可能的。在code是如下。

I want to show the connection speed(Latency?) of the users of my website. I think it can be possible by measuring XMLHttpRequest object request and response times. The code is as follow.

var t;
function ajsend(){
    var request = new XMLHttpRequest();
    var url;

    request.onreadystatechange = function(){
        if( request.readyState == 4 && request.status == 200 ){
            var u = new Date().valueOf();
            var timeTaken = u - t;
            var disp;
            if( timeTaken < 100 )
                disp = "Excellent! " + timeTaken + " milliseconds.";
            else if( timeTaken < 500 )
                disp = "Very Good! " + timeTaken + " milliseconds.";
            else if( timeTaken < 1200 )
                disp = "Normal! " + timeTaken + " milliseconds.";
            else if( timeTaken < 2000 )
                disp = "Poor! " + timeTaken + " milliseconds.";
            else
                disp = "Very Poor! " + timeTaken + " milliseconds.";
            document.getElementById("disp").innerHTML = disp;
        }
    };

    t = new Date().valueOf();
    url = "noscript.php";
    request.open("GET", url, true);
    request.send();
}

它的工作原理!但结果是来自浏览器的Web控制台的测量有些不同。那么,是不是从阿贾克斯还是最好的方式通过AJAX什么更好的办法?谢谢你。

It works! But the result is a bit different from the measurement of browser's Web Console. So, is it the best way from AJAX or any better way by AJAX? Thanks.

推荐答案

如果要比较的时间需要多长时间你的服务器开始响应请求,核对的readyState == 2 可能更好地工作。

If you want to compare the time on how long it takes for your server to start responding to the request, checking against readyState == 2 might work better.

在readyState的2,请求已接收的头从服务器,所以它应该是可用的稍微早于readyState的4

In readyState 2, the request has received headers from the server, so it should be available somewhat sooner than readyState 4.

另外请注意,JavaScript是不是在毫秒级精确的,所以你也可能得到一些差异,因为这一点。

Also note that JavaScript is not accurate on the millisecond level so you may also get some differences because of that.

 
精彩推荐
图片推荐