javascript - onClick时取消流,javascript

标签 javascript html css node.js onclick

我想做的事情背后的想法是,一旦我再次运行完全相同的函数,但使用不同的参数,就中断/完成一个函数。

现在我有一个随机字符流被发送到一个端点。

类获取此端点并允许流填充内容 View 。

我有一个选项卡,每次单击它时都会调用此填充函数。

我希望当我单击另一个选项卡或同一个选项卡时,该函数结束,停止使用以前的参数,然后使用新参数再次运行该函数。在单击同一个选项卡的情况下,它什么都不做。

下面是 HTML 正文、CSS、客户端的 JS 脚本,以及发送流的 node.js 服务器端。您应该能够或多或少地复制粘贴它,它就会运行。

不要忘记为 Node 安装 npm。只需运行 Node 代码即可启动服务器。

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();
}

服务器:

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();
}

最佳答案

您可以将 XMLHttpRequest xhr 存储在函数本身中,并在每次运行该函数时中止它。像这样(在你的 JS 文件中):

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() 方法:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

编辑:还要在回调中添加 getStreamNContentLocale.xhr = undefined;,否则它可能会在中止已完成的请求时返回错误。

关于javascript - onClick时取消流,javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213947/

相关文章:

javascript - 重新加载页面或浏览器后如何处理 Kaltura session 连接

javascript - 页面未在 JavaScript 中加载

HTML5 Canvas 颜色区分

javascript - 如何防止文本区域中的重复空格

css - 使用 CSS Transition 维护列表维度

javascript - 带有向下滑动面板的固定标题,当您向下滚动页面时该面板也保持固定

javascript - React js钩子(Hook)useEffect无限循环

javascript - 如何使用 ng-change 获取字段的值

html - 子菜单保持关注页面变化 Angular 2

html - 媒体查询不适用于 415px