本文實例講述了Javascript實現網絡監測的方法。分享給大家供大家參考。具體實現方法如下:
該代碼可監測網絡是否連接及網速的快慢狀態。
(function(){ var network = function(){ var monitor = this; /** * @param {Funcation} speedInterval */ var speedInterval = null; /** * @param {Function} networkInterval */ var networkInterval = null; /** * @param {Function} reNetworkInterval */ var reNetworkInterval = null; var time = 5000; /** * 獲取網絡連接狀態 */ var getConnectState = function(){ return navigator.onLine ? 1 : 0; }; /** * 網絡中斷 */ var disconnect = function(){ // TODO ... console.log("網速中斷"); window.clearInterval(reNetworkInterval); reNetworkInterval = null; endSpeed(); endNetwork(); window.setTimeout(function(){ reNetworkInterval = window.setInterval(function(){ if (getConnectState() == 1) { window.clearInterval(reNetworkInterval); reNetworkInterval = null; startSpeed(); startNetwork(); } else { window.clearInterval(reNetworkInterval); reNetworkInterval = null; disconnect(); } }, time); }, 2 * time); }; /** * 網絡速度 */ var speed = { /** * 網速過慢 */ bad : function(){ // TODO ... console.log("網速過慢"); window.setTimeout(function(){ if(getConnectState() == 1) { window.clearInterval(networkInterval); networkInterval = null; startSpeed(); } else { disconnect(); } }, 2 * time); }, /** * 網速中等 */ medium : function(){ // TODO ... console.log("網速中等"); }, /** * 網速極佳 */ great : function(){ // TODO ... console.log("網速極佳"); } }; /** * 開啟速度監測 * @private */ var startSpeed = function(){ window.clearInterval(speedInterval); speedInterval = null; if(getConnectState() == 1) { speedInterval = window.setInterval(function(){ var start = new Date().getTime(); if (getConnectState() == 1) { var img = document.getElementById("networkSpeedImage"); if (!!!img) { img = document.createElement("IMG"); img.id = "networkSpeedImage"; img.style.display = "none"; document.body.appendChild(img); } try { img.src = "http://www.baidu.com/img/baidu_jgylogo3.gif?_t=" + new Date().getTime(); img.onload = function(){ var end = new Date().getTime(); var delta = end - start; if (delta > 200) { speed.bad(); } else if (delta > 100) { speed.medium(); } else { speed.great(); } }; } catch(e){ speed.bad(); } } else { // TODO 網絡斷開 disconnect(); } }, time); }else { // TODO 網絡斷開 disconnect(); } }; /** * 停止速度監測 * @private */ var endSpeed = function(){ window.clearInterval(speedInterval); speedInterval = null; }; /** * 開啟網絡連接監測 * @private */ var startNetwork = function(){ if (getConnectState() == 1) { networkInterval = window.setInterval(function(){ if (getConnectState() == 0) { disconnect(); } }, time); } else{ disconnect(); } }; /** * 結束網絡連接監測 * @private */ var endNetwork = function(){ window.clearInterval(networkInterval); networkInterval = null; }; /** * 網絡監控開始 */ this.start = function(){ startNetwork(); startSpeed(); }; /** * 停止網絡監控 */ this.stop = function(){ endSpeed(); endNetwork(); }; }; window.network = new network(); }).call(this); // 調用的時候,直接調用network.start();
希望本文所述對大家的javascript程序設計有所幫助。