JavaScript内存模型

发布于 2024-12-18 10:55:58 字数 571 浏览 2 评论 0原文

是的,我知道在 Javascript 中要求一个正式的内存模型是一项无望的任务,所以我满足于“所有浏览器都遵循这些规则”之类的东西。

我的问题如下:我必须以定义的时间间隔将事件发送到服务器,但这样做时事件可能会添加到我的数组中,即:

function storeEvent(event) {
    // may be called at any time
    storedEvents.push(event);
}

function broadcastEvents() {
    if (storedEvents.length !== 0) {
        var eventString = JSON.stringify(storedEvents);
        storedEvents = [];
        // send eventString to server
    }
    window.setTimeout(broadcastEvents, BROADCAST_TIMER);
}

那里存在明显的竞争条件,甚至没有考虑丢失的内存屏障。

该怎么办?这里真的缺少 Java 内存模型..

Yes I'm aware that asking for a formal memory model in Javascript is a hopeless undertaking, so I'm settling for "All browsers follow these rules" or something.

My problem is the following: I have to send events in a defined interval to a server, but events may be added to my array while doing so, i.e.:

function storeEvent(event) {
    // may be called at any time
    storedEvents.push(event);
}

function broadcastEvents() {
    if (storedEvents.length !== 0) {
        var eventString = JSON.stringify(storedEvents);
        storedEvents = [];
        // send eventString to server
    }
    window.setTimeout(broadcastEvents, BROADCAST_TIMER);
}

There's an obvious race condition in there and not even think of the missing memory barriers.

What to do? Really missing the Java memory model here..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有任何竞争条件。

浏览器中的所有 JavaScript 代码都是单线程的。

setTimeout 回调将在 UI 线程上运行,同时不执行任何其他操作。

There isn't any race condition.

All JavaScript code in the browser is single-threaded.

The setTimeout callback will run on the UI thread while it isn't doing anything else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文