Based on your sample sheet, you already read the data in the cells before you lock your succeeding code and clear its content.
Your original code:
var data = ss.getRange("B1:B2").getValues();
if(data[0][0] == "" || data[1][0] == "")
return;
var lock = LockService.getScriptLock();
try{
lock.waitLock(1);//get the lock timing out in 1 millisecond
SpreadsheetApp.flush();
ss.insertRowBefore(7);
ss.getRange("A7").setValue(data[0][0]);
ss.getRange("B7").setValue(data[1][0]);
SpreadsheetApp.flush();
Utilities.sleep(10);//This is to make sure it takes at least 1 millisecond
lock.releaseLock();
ss.getRange("B1:B2").setValue("");
}
catch(e){
return;//It should generate a exception and end the script if the lock is not aquired
}
What it does?
- When you click submit button multiple times to execute your code, it will have n-times execution instance. As long as the clearing of cells don't take effect, each execution can write the data read from
B1:B2
.
Example:
Execution 1 started at 01:00:00.001 - already read the values in `B1:B2`
Execution 2 started at 01:00:00.005 - already read the values in `B1:B2`
Execution 3 started at 01:00:00.010 - already read the values in `B1:B2`
Execution 1 cleared B1:B2
content at 01:00:00.012. Hence you will have 3 copies of the submitted data. The writing of data in a new row was pended using the lock service, but the reading of data to add was not locked.
Solution
function submit() {
Utilities.sleep(1000);//simulate the upper part of the code
var ss = SpreadsheetApp.getActive().getSheetByName("spr1");
var lock = LockService.getScriptLock();
try{
lock.waitLock(1);//get the lock timing out in 1 millisecond
Logger.log("Locked: "+Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"yyyy-MM-dd'T'HH:mm:ss.SSS"));
var data = ss.getRange("B1:B2").getValues();
Logger.log(data);
if(data[0][0] == "" || data[1][0] == "")
return;
SpreadsheetApp.flush();
ss.insertRowBefore(7);
ss.getRange("A7").setValue(data[0][0]);
ss.getRange("B7").setValue(data[1][0]);
Utilities.sleep(10);//This is to make sure it takes at least 1 millisecond
ss.getRange("B1:B2").setValue("");
SpreadsheetApp.flush();
lock.releaseLock();
Logger.log("UnLocked: "+Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"yyyy-MM-dd'T'HH:mm:ss.SSS"));
}
catch(e){
return;//It should generate a exception and end the script if the lock is not acquired
}
Utilities.sleep(1000);//simulate the lower part of the code
}
Changes Done:
- Lock the script first before reading the data in
B1:B2
- Make sure to clear the content of
B1:B2
once it was added in a new row using flush()
before releasing the lock.
Output:
