This problem appeared recently ~August 25, 2022.
My onEdit
trigger relies on a sheet name and the script runs too long to get it. This is the smallest script to reproduce an error in my enviroment:
function onEdit(e) {
var t = new Date();
console.log('we are in onEdit!');
var sheetName = e.range.getSheet().getName();
console.log(sheetName);
console.log('We got sheet name. Time past = ' + (new Date() - t));
}
The function range.getName()
works too slow, and the script is timed out.
I did not see this behavior any time before. Other sample: SpreadsheetApp
. In my other file this line takes 30 sec.:
SpreadsheetApp.openById(id);
Reproduce the error
Here's the file with minimal code needed to reproduce the error:
onEdit Crash Test ➡️ e.range.getSheet().getName()
Please make a copy.
To Reproduce the onEdit
Error
- Print 1 in the first cell
- Immediately press enter and Print 2
- Repeat it a few times
- Go to the script editor and see execution time
It has a few formulas and the script works fast.
My goal is to understand why formulas cause sheet.getName()
method to slow down.
Error
Exceeded maximum execution time
The max. time for onEdit is 30 sec. Tests showed that sheet.getName()
worked too long. I cannot see the edited sheet name without the getName()
function as it is inside a trigger.
My Fix
Even Lock and Cache did not resolve this:
Injection
/** 🦿 Injection. Use Cache to Speed Up `getName()` method */
var lock = LockService.getScriptLock();
try {
lock.waitLock(30000); // wait 30 seconds for others'
} catch (e) {
throw 'Could not get Sheet Name in 30 sec. :(';
}
var sheetNameCacheKey = 'sheetNameforThoseWhoForgotten';
var c = CacheService.getUserCache();
var sheetNameFromCache = c.get(sheetNameCacheKey);
if (sheetNameFromCache) {
sets.sheetName = sheetNameFromCache;
console.log('Prolongated Cache Life!');
c.put(sheetNameCacheKey, sets.sheetName, 5);
} else {
// This function is actually needed,
// but does not work fast
// ⏳🐌🐌🐌🐌🐌🐌🐌
sets.sheetName = sets.sheet.getName();
// Write Sheet Name to Memory for 5 seconds
c.put(sheetNameCacheKey, sets.sheetName, 5);
console.log('Added Sheet Name to Cache!');
}
lock.releaseLock();
/** 🦿 End of Injection */
This code makes my trigger more stable, but it still fails occasionally.
Speed Tests
time to read sheet name is: 151766
This is almost 3 minutes! But this number changes and occasionally it may take ~150 ms to run.
Notes
My guess is this error caused by the latest big update and new functions for Google Sheets:
I think so because this problem comes in hand with IMPORTRANGE
error:
Import Range internal error.
onEdit_DVL_(e)
so what exactly is causing the problem?