speedtest/Frontend/server_selector.min.js
2018-12-20 18:18:58 +01:00

1 line
1.8 KiB
JavaScript

var PING_TIMEOUT=1e3,USE_PING_TIMEOUT=!0;function ping(url,result){var xhr=new XMLHttpRequest,t=(new Date).getTime();if(xhr.onload=function(){if(0==xhr.responseText.length){var instspd=(new Date).getTime()-t;try{var p=performance.getEntries(),d=(p=p[p.length-1]).responseStart-p.requestStart;d<=0&&(d=p.duration),0<d&&d<instspd&&(instspd=d)}catch(e){}result(instspd)}else result(-1)}.bind(this),xhr.onerror=function(){result(-1)}.bind(this),xhr.open("GET",url),USE_PING_TIMEOUT)try{xhr.timeout=PING_TIMEOUT,xhr.ontimeout=xhr.onerror}catch(e){}xhr.send()}/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)&&(USE_PING_TIMEOUT=!1);var PINGS=3,SLOW_THRESHOLD=500;function checkServer(server,done){var i=0;if((server.pingT=-1)==server.server.indexOf(location.protocol))done();else{var nextPing=function(){i++!=PINGS?ping(server.server+server.pingURL,function(t){0<=t?((t<server.pingT||-1==server.pingT)&&(server.pingT=t),t<SLOW_THRESHOLD?nextPing():done()):done()}.bind(this)):done()}.bind(this);nextPing()}}function selectServer(serverList,result){var i=0,done=function(){for(var bestServer=null,i=0;i<serverList.length;i++)-1!=serverList[i].pingT&&(null==bestServer||serverList[i].pingT<bestServer.pingT)&&(bestServer=serverList[i]);result(bestServer)}.bind(this),nextServer=function(){i!=serverList.length?checkServer(serverList[i++],nextServer):done()}.bind(this);nextServer()}var CONCURRENCY=4;function fastSelectServer(serverList,result){for(var serverLists=[],i=0;i<CONCURRENCY;i++)serverLists[i]=[];for(i=0;i<serverList.length;i++)serverLists[i%CONCURRENCY].push(serverList[i]);var completed=0,bestServer=null;for(i=0;i<CONCURRENCY;i++)selectServer(serverLists[i],function(server){null!=server&&(null==bestServer||server.pingT<bestServer.pingT)&&(bestServer=server),++completed==CONCURRENCY&&result(bestServer)}.bind(this))}