js 中断函数执行_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);

Second does trigger events:

setInterval(function() {

store.addElement('bye');

}, 7000);

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

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 is single-threaded. A function cannot be interrupted, so you can be sure each function block will complete before another begins.

(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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值