原理
发起一个 Ajax 请求,开始记录一个时间,Ajax 返回 sucess 时的,记录这个时间为耗时时间,耗时时间-开始时间得出时间就是耗时的时间,通过耗时时间结果来根据 200,500 来设置辨别网络快慢
代码
new Date ().getTime () 是获取毫秒
$.ajax ({
url: "/study/lag",
timeout: 3000,
success: function (data, text, xhr){
if (xhr.status == 200){
var lag = new Date ().getTime () - start;
if (lag < 200){
$("#lag").attr ("title", "网络畅通:"+lag+"ms").attr ("src", "/study/static/images/ic_network_cell_black_24dp.png")
}else if (lag < 500){
$("#lag").attr ("title", "网络较慢:"+lag+"ms").attr ("src", "/study/static/images/ic_network_cell_black_24dp_lag.png")
}else{
$("#lag").attr ("title", "网络很慢:"+lag+"ms").attr ("src", "/study/static/images/ic_network_cell_black_24dp_block.png")
}
}else{
$("#lag").attr ("title", "网络未连接").attr ("src", "/study/static/images/ic_network_cell_black_24dp_not.png")
}
},
error: function (){
$("#lag").attr ("title", "网络未连接").attr ("src", "/study/static/images/ic_network_cell_black_24dp_not.png")
},
complete: function (){
checkLag ();
}
})
上面只是一个请求,如果我们想隔 1 分钟检测一次呢,怎么办
写个函数,然后定时任务
// 延迟
function checkLag (){
setTimeout (function (){
var start = new Date ().getTime ()
$.ajax ({
url: "https://www.baidu.com",
timeout: 3000,
success: function (data, text, xhr){
if (xhr.status == 200){
var lag = new Date ().getTime () - start;
if (lag < 200){
$("#lag").attr ("title", "网络畅通:"+lag+"ms").attr ("src", "/study/static/images/ic_network_cell_black_24dp.png")
}else if (lag < 500){
$("#lag").attr ("title", "网络较慢:"+lag+"ms").attr ("src", "/study/static/images/ic_network_cell_black_24dp_lag.png")
}else{
$("#lag").attr ("title", "网络很慢:"+lag+"ms").attr ("src", "/study/static/images/ic_network_cell_black_24dp_block.png")
}
}else{
$("#lag").attr ("title", "网络未连接").attr ("src", "/study/static/images/ic_network_cell_black_24dp_not.png")
}
},
error: function (){
$("#lag").attr ("title", "网络未连接").attr ("src", "/study/static/images/ic_network_cell_black_24dp_not.png")
},
complete: function (){
checkLag ();
}
})
}, 1000 * 60)
}
checkLag ()
控制台
function checkLag (){
setTimeout (function (){
var start = new Date ().getTime ();
$.ajax ({
url: "https://www.heibaiketang.com",
timeout: 3000,
success: function (data, text, xhr){
if (xhr.status == 200){
var lag = new Date ().getTime () - start;
if (lag < 200){
console.log ("网络畅通:"+lag+"ms");
}else if (lag < 500){
console.log ("网络较慢:"+lag+"ms");
}else{
console.log ("网络很慢:"+lag+"ms");
}
}else{
console.log ("网络未连接");
}
},
error: function (){
console.log ("网络未连接");
},
complete: function (){
checkLag ();
}
})
},10*1000);
}
checkLag ();