从事件中访问变量时,我是否必须在Javascript中锁定变量

时间:2016-10-06 12:29:36

标签: javascript events parallel-processing synchronization locking

以下示例代码将后续调用方法中的某些数据排入方法,并在某个超时或事件(如RAF)之后一次性发送所有排队数据:

Live fiddle

let _queue;

function send(data) {     
  if (_queue) {
    _queue.push(data);
  } else {
    _queue = [ data ];
    // The timeout could also be replaced by some event like RAF etc.
    window.setTimeout(() => {
        // Send all queued data as 1 batch request...
        _queue = undefined;
    }, 100);
  }
}

// Those calls actually come from "unpredictable" events like mouse clicks etc.
send('1');
window.setTimeout(send.bind(this, '2'), 50);
window.setTimeout(send.bind(this, '3'), 80);

我是否正确地假设我根本不需要担心锁定_queue变量,因为JS是单线程的,并且不可能有并行访问它,无论如何send调用的来源是什么(setTimeout,RAF,UI事件,......)?

0 个答案:

没有答案