I need to implement the queue of events (=updates on the server). New events will be added to this queue when user changes the slider, presses buttons etc. Each event will contain the following properties:
- device id (the action will be applied to that device on the server)
- action (set, get etc.)
- value (the value, which should be used in the action)
New event should be added there at the end. But in case there is already event for the same device id and with the same action, then this event should be updated with new value. How should I do that?
I’ve drafted the following:
var inCall = false;
var queueArrayDevices = new Array();
var queueArrayActions = new Array();
var queueArrayValues = new Array();
// add call to the queue, at the end
function addAPICall(device, action, value){
// should NOT add event here, if device and action already exists
// should update the value instead
queueArrayDevices.push(device);
queueArrayAсtions.push(action);
queueArrayValues.push(value);
}
function doAPICall(device, action, value){
inCall = true;
// call server here
// if not successful, we should add this item to the queue again
inCall = false;
}
function callAPIQueue(){
if(!inCall && queueArrayDevices.length > 0){
device = queueArrayDevices.shift();
action = queueArrayAсtions.shift();
value = queueArrayValues.shift();
doAPICall(device, action, value);
}
}
// start queue processing
setInterval(callAPIQueue, 400);
I use jquery mobile, probably it can help me to simplify such queue creation?
First of, you should only have one array holding an event object, otherwise you are really over complicating it for yourself.
next just loop over the events and see if one of the same device/action already exists when a new event is added.
try to do it something like this: