JavaScript函数执行可以被中断吗? [英] Can JavaScript function execution be interrupted?

查看:520
本文介绍了JavaScript函数执行可以被中断吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个存储数据的对象。

Having an object to store data.

var store = {
    elements: [],
    eventsEnabled: true,
    addElement: function(element) {
        this.elements.push(element);
        if (this.eventsEnabled) {
            // Code that triggers event, calls handlers... whatever
        }
    }
};

存储数据的行为来自两个事件(两种生产者)。第一个生产者不会触发任何事件:

The act of storing data comes from two events (kind of two producers). First "producer" does not trigger any event:

setInterval(function() {
    store.eventsEnabled = false;
    store.addElement('hello');
    store.eventsEnabled = true;
}, 12000);

秒确实触发事件:

setInterval(function() {
    store.addElement('bye');
}, 7000);

问题是,第二个生产商可以打破第一个生产者的执行流程吗?

The question is, can the second producer break execution flow of first producer?

我的意思是,如果生产者1禁用事件,并且在完成执行之前(因此在再次启用事件之前),生产者2开始执行并添加其元素,则不会触发任何事件。那可能吗?会发生这种情况吗?

I mean, if producer 1 disables events and, before finishing execution (and therefore before events are enabled again), producer 2 starts its execution and adds its element, then no events will be triggered. Is that possible? Can that happen?

如果是这样,如何将此代码转换为线程安全类型?

If so, how can this code be converted to be kind-of thread-safe?

推荐答案

JavaScript是单线程的。函数不能被中断,因此您可以确保每个函数块在另一个函数块开始之前完成。

JavaScript is single-threaded. A function cannot be interrupted, so you can be sure each function block will complete before another begins.

(但是,如果函数进行异步调用,则其他函数可能会执行在异步操作开始之前。在你的代码中不会发生这种情况,除了 setTimeout 调用之外,我可以看到,你可以确定它们会在正确的订单。)

(However, if a function makes an asynchronous call, other functions may execute before the asynchronous operation starts. That doesn't happen in your code, though, that I can see, besides the setTimeout calls, and you can be sure those will execute in the correct order.)

这篇关于JavaScript函数执行可以被中断吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆