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