2016-07-25 34 views
1

私は同じマシン上のWebサーバーインターフェイスを毎秒ポーリングするWebワーカーを取得しようとしています。私が読んだ記事の多くは、setIntervalを避け、代わりにsetTimeoutを使用すると述べていますが、Jqueryの代わりにAJAXを使用する例はまだありません。setTimeoutを使用したAJAX Webworkerのポーリング

私がこれまで持っているコードは以下の通りです:

(function poll() { 
    setTimeout(function() { 
    var xhr = new XMLHttpRequest(); 
    xhr.onload = function() { 
     if (xhr.status === 200) { 
      responseObject = JSON.parse(xhr.responseText); 
      var newContent = ''; 
      newContent += responseObject.cmd; 
      console.log(newContent); 
     } 
    } 
    xhr.open('GET', 'http://localhost:8194/screen_update/1000', true); 
    xhr.send(null); 
    setTimeout(poll, 1000); 
}, 1000); 
})(); 

優先出力は、サーバに応答が通ってくるためにのために、理論的には十分すぎるほどであるべき秒ごとにポーリングするだろう。一度に1つのリクエストだけが必要です。リクエストが1秒以上かかると、キューに入れるのではなく要求をダンプして新しいリクエストを発行します。

上記のコードは大丈夫ですが、2秒間は完了しませんので、明らかにsetTimeoutがどこかで混ざっています。このコードはどこで修正できますか?

+0

は、ステータスコードは、はい、おお200 – epascarello

答えて

0

ajaxが終了したかどうかを決定する変数を定義します。 ajaxがまだ終了していないときに関数が呼び出された場合、関数を終了して次の呼び出しを待つことができます。

var stillWorking = false; 

(function poll() { 
    if(stillWorking) return false; 
    stillWorking = true; 
    setTimeout(function() { 
    var xhr = new XMLHttpRequest(); 
    xhr.onload = function() { 
     if (xhr.readyState == 4) stillWorking = false; 
     if (xhr.status === 200) { 
      responseObject = JSON.parse(xhr.responseText); 
      var newContent = ''; 
      newContent += responseObject.cmd; 
      console.log(newContent); 

     } 
    } 
    xhr.open('GET', 'http://localhost:8194/screen_update/1000', true); 
    xhr.send(null); 
    setTimeout(poll, 1000); 
}, 1000); 
})(); 
0

あなたはAJAXの応答を受け取ったときに同じ機能を呼び出すことができます。このようにして、現在AJAXが処理中であるかどうかを確認する必要はありません。

function poll() { 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange= function() { 

     if (xhr.status === 200) { 
      responseObject = JSON.parse(xhr.responseText); 
      var newContent = ''; 
      newContent += responseObject.cmd; 
      console.log(newContent); 

     } 
     if (xhr.readyState == 4) 
     { 
      setTimeout(function(){ poll();},1000); 
     } 
    } 
    xhr.open('GET', 'http://localhost:8194/screen_update/1000', true); 
    xhr.send(null); 
}; 
setTimeout(function(){ poll();},1000); 

あなたはonloadのコールバックを使用したい場合は、コールバックコードが

xhr.onload= function() { 
     if (xhr.status === 200) { 
      responseObject = JSON.parse(xhr.responseText); 
      var newContent = ''; 
      newContent += responseObject.cmd; 
      console.log(newContent); 

     } 
     setTimeout(function(){ poll();},1000); 
    } 
+0

でタイムアウトを入れて...我々は確認する必要があり状態が4の場合、ajax状態。 –

+0

でない場合、これは、AJAX要求を停止しますonoad –

+0

私はコードを変更しました。 –

0

する必要があります私は..ほんの数日前にいることを行なったし、それが最もエレガントではないかもしれないが、それはとてもうまく動作します遠い 私は、作業者にメインJSではなく、タイムアウト/チェック間隔を処理させます。だから私はUIが処理する必要がないことがもう一つあると思います。ここに私のワーカーのコードは次のとおりです。

function checkStatus() {  
    console.log("statusCheck started"); 

    var ajaxRequest; 
    try { ajaxRequest = new XMLHttpRequest(); // Opera 8.0+, Firefox, Safari 
    } catch (e) { try { // Internet Explorer Browsers 
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (e) { try { 
       ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch (e) { // Something went wrong 
       console.error("AJAX not possible"); 
       return false; 
      } 
     } 
    } 


    // Create a function that will receive data sent from the server 
    ajaxRequest.onreadystatechange = function() { 
    if(ajaxRequest.readyState == 4) { 

      self.postMessage(ajaxRequest.responseText); 

      var timer; 
      timer = self.setTimeout(function(){ 
       checkStatus(); 
      }, 1000); 

     } 
    } 

    ajaxRequest.open("GET", "/worker_statusCheck.php", true); 
    ajaxRequest.send(null); 

} 



this.onmessage = function(e){ 
    checkStatus(); // the message comes in just once on pageLoad 
}; 
+0

目頭:これは毎秒チェックしません。これは、成功したAJAX応答後に1秒後に再びチェックします。 –

0

あなたがHTML5 WebWorkerを使用しているので、おそらく、あなたは約束(https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)を使用するwindow.fetchを使用することができ、私は、ブラウザのサポートはほぼ同じだと思います。ここで

は一例です:

((url, INTERVAL, configs) => { 
 
    const MAX_ERRORS = 4; 
 
    let errors = 0; 
 
    var poll =() => window.setTimeout(getData, INTERVAL); 
 
    
 
    function getData() { 
 
    return window 
 
     .fetch(url, configs) 
 
     .then(res => res.json()) 
 
     .then(data => { 
 
     errors = 0; 
 
     poll();  
 
     return data; 
 
     }) 
 
     .then((data) => { 
 
     console.log("new data available", data); 
 
     }) 
 
     .catch(() => { 
 
     if(errors >= MAX_ERRORS) { 
 
      console.log("GIVING UP"); 
 
      return; 
 
     } 
 
     
 
     errors += 1; 
 
     return poll(); 
 
     }) 
 
    ; 
 
    } 
 
    
 
    
 
    return poll(); 
 
})("http://jsonplaceholder.typicode.com/posts/1", 1000, { 
 
    method: 'GET' 
 
});

関連する問題