延迟计算通过AJAX [英] Latency Calculation by AJAX

查看:113
本文介绍了延迟计算通过AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想告诉我的网站的用户的连接速度(延迟?)。我认为它可以通过测量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.

这篇关于延迟计算通过AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆