I have 2 functions that each modify a parameter that is passed to them.
var data = [];
var DoStuff = function( $div , data )
{
var $D = $div;
var D = data;
var socket = $.atmosphere;
var stuff = {
onMessage: function(message)
{ // when a message is asynch. received over websocket
D.push( { "a": "b" } );
D.push( { "y": "z" } );
$D.append( JSON.stringify(D) );
return message;
}
}
this.start = function()
{
var socketStream = socket.subscribe( stuff );
return socketStream;
}
}
$(function(){
var $div = $('#div');
var doStuff = new DoStuff( $div , data );
data.push( { "w": "x" } );
$div.append( JSON.stringify(data) );
var stream = doStuff.start();
});
Sometimes after everything is all said and done, the array data
contains both objects:
data: [
{ "w": "x" },
{ "y": "z" }
]
But sometimes it contains only the first object:
data: [
{ "w": "x" }
]
If I put a breakpoint on DoStuff.a return true;
, D
usually contains both objects. But about 10% of the time, D
does not contain the first object (only the second), YET, data
contains only the first. D
is a reference to data
, so how can they be out of synch?
Edit I tried using setTimeout() to make each and then both push()
wait, but that did not cause different outcome in any of the 3 cases.
I think it can't be a race condition because then something would get overwritten, but that's not happening. a:b and y:z are missing. If that were the case, either a:b or y:z should still be present (along with w:x).