2017-04-04 11 views
0

私がやりたいことの背後にあるアイデアは、同じ機能をもう一度実行した後に、別のパラメータでブレーク/フィニッシュすることです。onClick時にストリームをキャンセルする、JavaScript

今、エンドポイントに送信されるランダムな文字のストリームがあります。

クラスはこのエンドポイントを取得し、ストリームがコンテンツビューに入力できるようにします。

私はクリックするたびにこの母集団関数を呼び出すタブを持っています。

別のタブまたは同じタブをクリックすると、関数が終了し、以前のパラメータを使用しなくなり、新しいパラメータで関数を再度実行するようにしたいと思います。同じタブをクリックすると、何もしません。

以下は、HTML本体、CSS、クライアント側のJSスクリプト、ストリームを送信するnode.jsサーバー側です。あなたは多かれ少なかれこれを貼り付けることができるはずですし、それが実行されます。

ノードのnpm installを忘れないでください。ノードコードを実行してサーバーを起動してください。

HTML:

<div class="tab-bar"> 
     <button class="tab" onclick="getStreamNContentLocale('stream_1')">London</button> 
     <button class="tab" onclick="getStreamNContentLocale('stream_2')">Paris</button> 
     <button class="tab" onclick="getStreamNContentLocale('stream_3')">Tokyo</button> 
    </div> 
    <div class="content"> 
     <div id="stream_1"> 
     </div> 
     <div id="stream_2"> 
     </div> 
     <div id="stream_3"> 
     </div> 
    </div> 
    <script src="js/index.js"></script> 

CSS:

.tab-bar { 
    height: 40px; 
    width: 100%; 
    background-color: black; 
} 

.tab { 
    color: white; 
    font-size: 100%; 
    float: left; 
    padding: 9px 16px; 
    vertical-align: middle; 
    background-color: inherit; 
} 

.content { 
    border: 1px solid #ccc; 
    overflow: auto; 
    height: 200px; 
    width: 100%; 
} 

JS:

console.log((new Date()).toLocaleString()); 

function getStreamNContentLocale(contentID) { 
    let xhr = new XMLHttpRequest(), 
     streamArray = [], 
     snapshotsSent = 0; 

    xhr.open('GET', `/stream`); 
    xhr.seenBytes = 0; 
    xhr.onreadystatechange =() => { 
     if (xhr.readyState > 2) { 
      if (snapshotsSent < 30) { 
       streamArray.push("Snapshot sent " + (new Date()).toLocaleString() + "\n" + xhr.responseText.substring(xhr.seenBytes, xhr.responseText.length)); 
       document.querySelector(`#${contentID}`).innerText = streamArray; 
      } else if (snapshotsSent >= 30) { 
       streamArray.shift(); 
       streamArray.push("Snapshot sent " + (new Date()).toLocaleString() + "\n" + xhr.responseText.substring(xhr.seenBytes, xhr.responseText.length)); 
       document.querySelector(`#${contentID}`).innerText = streamArray; 
      } 
      xhr.seenBytes = xhr.responseText.length; 
     } 
     snapshotsSent++; 
     /********************************************************************************************** 
     * xhr.responseText.substring(xhr.seenBytes, xhr.responseText.length) is each snapshot we GET * 
     * snapshotsSent is the number of snapshots we have actually gotten so far in this session * 
     **********************************************************************************************/ 
    }; 
    xhr.send(); 
} 

SERV ER:

let express = require('express'), 
    app = express(), 
    bodyParser = require('body-parser'), 
    path = require('path'); 

init(function() { 
     callback(null); 
    }); 

function init(callback) { 
    app.use(bodyParser.json()); 

    app.use(bodyParser.urlencoded({ 
     extended: true 
    })); 

    app.use(express.static(path.join(__dirname, "../../views"))); 

    app.get('/', function(req, res) { 
     res.sendFile(path.join(__dirname, "../../views/index.html")); 
    }); 

    app.get('/stream', (req, res) => { 
     console.log('sending stream to /stream'); 
     setInterval(() => { 
      res.write(Math.random(16).toString(36).substring(2) + "\n"); 
     }, 200); 
    }); 

    app.listen(8000,() => { 
     console.log("Listening on port 8000"); 
    }); 

    callback(); 
} 

答えて

1

あなたは関数自体にXMLHttpRequest xhrを保存し、それをあなたが関数を実行するたびに中止することができます。この(あなたのJSファイル内)のように:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

EDIT::また、完成要求を中止する場合には、エラーを返すことがあり、他の、あなたのコールバックでgetStreamNContentLocale.xhr = undefined;を追加

function getStreamNContentLocale(contentID) { 

    if(getStreamNContentLocale.xhr !== undefined) 
     getStreamNContentLocale.xhr.abort(); 

    getStreamNContentLocale.xhr = new XMLHttpRequest(), 
     streamArray = [], 
     snapshotsSent = 0; 

    // the rest of your code goes here 
} 

abort()方法を参照してください。

+0

ああ、私が関数を実行するたびに、 'getStreamNContentLocale.xhr'が定義されているかどうかを調べることでストリームが既に実行されているかどうかを確認します。右? –

+0

まさに:) あなたが必要としていたものであれば、この回答を有効にすることを忘れないでください。 –

+0

私たちはこれをテストしています。 –

関連する問題