so i am implementing in javascript this feature: when the document is opened by the user its data gets saved every 10 seconds and when the user closes it is saved one more time. It works seemingly well. Here is the implementation:
var data = "blabla";
var saveagain = false;
var t1;
function onDocumentOpen() {
saveagain = true;
savedata();
}
function onDocumentClose() {
saveagain = false;
savedata();
}
function savedata() {
if (!saveagain) clearTimeout(t1);
SaveDataAjaxCall(data, function() {
//data was saved
if (saveagain) t1 = setTimeout("savedata()", 10000);
});
}
I was wondering if my approach is correct and if it can lead to some possible race condition in extreme circumstances such as:
when the savedata() instance called from onDocumentClose() is after the if(!saveagain) step, the savedata() instance called from the previous timer of the setTimeout() is before that step, so it gets to be called once more. Can this or anything more weird happen ?
Thanks in advance
EDIT:
After considering T.J. Crowder's and Bengi's comments I finalized the code as such:
var data = "";
var saveagain = false;
var t1;
var beingsaved = false;
function onDocumentOpen() {
saveagain = true;
savedata();
}
function onDocumentClose() {
saveagain = false;
savedata();
}
function saveData() {
if (beingsaved) {
if (!saveagain) setTimeout(saveData, 100);
return false;
}
beingsaved=true;
if (!saveagain) clearTimeout(t1);
data=getData();
SaveDataAjaxCall(data, function() {
//data was saved
beingsaved=false;
if (saveagain) t1 = setTimeout(saveData, 10000);
});
}
I think I have handled every occasion now. I think the beingsaved solution is equal to the atomic countr that T.J Crowder suggested.
EDIT2: Hm, I'm not sure i solved it because there may be a case when if(beingsaved) gets evaluated by the setTimeout call JUST before the beingsaved is set to true by the onDocumentClose call. Can this happen ?
setTimeout-setTimeout(savedata, 10000)