2016-03-31 9 views
0

インターネット接続(正常に動作する)をチェックする関数と、20秒ごとにページを更新する関数を作成しています。私が取り組んできた別の機能は、インターネットの状態が変化し、リフレッシュ機能が停止したときに検出します。インターネットが再びオンラインになると、リフレッシュ機能が再び開始されます。私は複数の修正を試みましたが、何も動作していません。インターネット接続はその後、リフレッシュ機能が再び起動しない、オンラインに戻るまでJavascript - 関数からclearIntervalを使用した後にsetIntervalを再アクティブ化する

function checkNetConnection() 
{ 
    var xhr = new XMLHttpRequest(); 
    var file = "http://i.imgur.com/FIKb6D8.png"; 
    var r = Math.round(Math.random() * 10000); 
    xhr.open('HEAD', file + "?rand=" + r, false); 
    try { 
     xhr.send(); 
     if (xhr.status >= 200 && xhr.status < 304) { 
      return true; 
     } else { 
      return false; 
     } 
    } catch (e) { 
     return false; 
    } 
} 

function modalCheck() 
{ 
    var status = checkNetConnection(); 
    if(status == false) { 
     document.getElementById('mymodal').style.display = "block"; 
    } else { 
     document.getElementById('mymodal').style.display = "none"; 
    } 
} 

var int1 = setInterval(modalCheck, 7000); 

function refreshPage() 
{ 
    var state = checkNetConnection(); 
    if(state == false) 
    { 
     clearInterval(int2); 
    } else {      
     location.reload(true); 
     alert("PAGE RELOADED!"); /* Testing purposes! */ 
    } 
} 

var int2 = setInterval(refresh, 12000); 

すべてが正常に動作します:

はここにいくつかのコードです。これが私が修正しようとしていることです。

ありがとうございました。

+0

[非同期呼び出しからの応答を返すにはどうすればよいですか?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-電話) –

答えて

1

まず、実際にはページのリフレッシュを停止することはありません。 refresh()機能が存在しないため、

function modalCheck() 
{ 
    var status = checkNetConnection(); 
    if(status == false) { 
     document.getElementById('mymodal').style.display = "block"; 

     clearInterval(int2); //Connection lost! DO NOT REFRESH 
     int2 = null; //So the next if statement can detect whether the interval is going or not 

    } else { 
     document.getElementById('mymodal').style.display = "none"; 

     if(!int2) { //So interval isn't doubled up! 
      int2 = setInterval(refresh, 12000); //Connection regained! 
     } 
    } 
} 

第二に、あなたのページは、おそらく更新されません:

setInterval(refresh, 12000); //should be "refreshPage" 

それ

あなたのインターネット・チェック機能は、このように、リフレッシュを停止する必要がありますすべてでなければならない!あなたのプロジェクトがうまくいくことを願って!

+1

ありがとうございました!完璧に動作します。ええ、古いコードをコピーしたので、リフレッシュが誤って名前が付けられたのです。 – clintgx

関連する問題