首页 > 代码库 > 测时延

测时延

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here222222222222</title>

<script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.8.0.js"></script>

<script type="text/javascript">

$.ping = function(option) {

var ping, requestTime, responseTime;

var getUrl = function(url) {

// 保证url带http://

var strReg = "^((https|http)?://){1}"

var re = new RegExp(strReg);

return re.test(url) ? url : "http://" + url;

}

$.ajax({

url : getUrl(option.url) + ‘/‘ + (new Date()).getTime() + ‘.html‘,

// 设置一个空的ajax请求

type : ‘GET‘,

dataType : ‘html‘,

timeout : 10000,

beforeSend : function() {

if (option.beforePing)

option.beforePing();

requestTime = new Date().getTime();

},

complete : function() {

responseTime = new Date().getTime();

ping = Math.abs(requestTime - responseTime);

if (option.afterPing)

option.afterPing(ping);

}

});


if (option.interval && option.interval > 0) {

var interval = option.interval * 1000;

setTimeout(function() {

$.ping(option)

}, interval);

// option.interval = 0; // 阻止多重循环

// setInterval(function(){$.ping(option)}, interval);

}

};

</script>

<script type="text/javascript">

function t() {

$.ping({

url : ‘http://www.9188.com/‘,

beforePing : function() {

$(‘#msg0‘).html(‘‘)

},

afterPing : function(ping) {

$(‘#msg1‘).html(ping)

},

interval : 5

});


}

</script>

</head>

<body>

<a href="javascript:;" onclick="t();">reqServer</a>

<br>

   <div id="msg0"></div>

   <div id="msg1"></div>

</body>

</html>


测时延