我正在添加定期自动保存用户工作的功能。首先,我想防止自动保存和用户生成的保存同时运行。因此,我们有以下代码(我省略了大部分代码,这不是一对一的,但应足以传达思想):
var isSaving=false;
var timeoutId;
var timeoutInterval=300000;
function save(showMsg)
{
//Don't save if we are already saving.
if (isSaving)
{
return;
}
isSaving=true;
//disables the autoSave timer so if we are saving via some other method
//we won't kick off the timer.
disableAutoSave();
if (showMsg) { //show a saving popup}
params=CollectParams();
PerformCallBack(params,endSave,endSaveError);
}
function endSave()
{
isSaving=false;
//hides popup if it's visible
//Turns auto saving back on so we save x milliseconds after the last save.
enableAutoSave();
}
function endSaveError()
{
alert("Ooops");
endSave();
}
function enableAutoSave()
{
timeoutId=setTimeOut(function(){save(false);},timeoutInterval);
}
function disableAutoSave()
{
cancelTimeOut(timeoutId);
}
我的问题是这段代码是否安全?主流浏览器是否只允许同时执行单个线程?
我想到的一个想法是,如果我们正在自动保存数据,用户点击保存却没有响应会更糟糕(我知道如何修改代码来解决这个问题)。还有其他问题吗?