Here is the scene about my problem.
I make a var dataCache, which buffers the data I achieve from remote server. I update dataChache every 30s, like this,
setInterval(function(){ instance.loadJsonFromRemote(configuration.dataUrl,function(data){ instance.dataCache = data; }); }, 30000);
and dataCache probably would be accessed exactly at the same time when it’s being updated.
For example,
var cool = instance.dataCache.cool
the code above runs while the data updating code runs,
instance.dataCache = data;
I guess the possible solution would be lock dataCache up while it is being accessed, if no one accesses it, it can be set.
I probably need something like lock in C#, but I don’t really know how to do it in JavaScript, or maybe it is not even a problem in JavaScript, coz JS is single threaded and it works fine. I’m not very familiar with JS.
Advertisement
Answer
There is no lock mechanism because javascript executes as single threaded.
The reason for confusion for people who came from a multi-threaded environment is that javascript always works like “async” way. But that is not really the case.
Javascript works with “callbacks” internally when some event is happened it will execute its callbacks that can be a bit tricky for a Java/.Net developer. Javascript always works on a single thread and nothing executes simultaneously, it has “javascript execution cycle” (See For Event Loop) that can be said a simple while(1) {} code executes code over and over again in each cycle your callbacks are initiated and etc.
The only possible solution for your case would be a callback from the setTimeout function that will trigger your update scenario.