最近在做一个需求时要考虑到网络环境是否能够访问,于是写了一段代码
function ping(address) {
var img = new Image();
var start = new Date().getTime();
var hasFinish = false;
img.onload = function() {
if ( !hasFinish ) {
hasFinish = true;
console.log('Ping ' + address + ' success. ');
}
};
img.onerror = function() {
hasFinish = false;
console.log('Ping ' + address + ' fail.. ');
};
img.src = address + '/?' + start;
setTimeout(()=>{
if(hasFinish){
hasFinish = false
console.log('There is a problem with your network, please refresh the page and try again.');
}
},1500)
}
ping('https://developers.facebook.com/favicon.ico')