I have the following code for a Google Sheet which utilises a Utilities.sleep() call.
Problematically, both highlightChildren()
and unhighlightChildren()
are executed after the Utilities.sleep()
call and I can't figure out why.
function onOpen() {
var ui = SpreadsheetApp.getUi()
ui.createMenu('OKRs').addItem('Show linked Key Results', 'getLinkedKeyResults').addToUi()
}
var highlightChildren = function(rangeList) {
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRangeList(rangeList).setBackground('#ffd966')
}
var unhighlightChildren = function(rangeList) {
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRangeList(rangeList).setBackground('#ffffff')
}
function extendChildrenRefs(stringRefs) {
return stringRefs.replace(/C/gi, 'B') + ',' + stringRefs
}
function getLinkedKeyResults() {
var scriptProperties = PropertiesService.getScriptProperties()
var ss = SpreadsheetApp.getActiveSpreadsheet()
var parentRef = ss.getActiveCell().getA1Notation()
var children = extendChildrenRefs(scriptProperties.getProperty(parentRef)).split(',')
highlightChildren(children)
Utilities.sleep(4 * 1000)
unhighlightChildren(children)
}
/**
* Links a parent key result progress to child key results, storing them in memory. Otheriwse, a direct clone of AVERAGE().
*
* @param {"value1, value2, value3..."} values The child key result values to consider when calculating parent key result progress.
* @return The average of range of value.
* @customfunction
*/
function LINKKEYRESULTS(values) {
if (arguments.length < 2) throw new Error('You must pass at least two key result values!')
var ss = SpreadsheetApp
var scriptProperties = PropertiesService.getScriptProperties()
var formula = ss.getActiveRange().getFormula()
var args = formula.match(/=\w+\((.*)\)/i)
var parentRef = ss.getActiveRange().getA1Notation()
var childrenRefs = args[1]
scriptProperties.setProperty(parentRef, childrenRefs)
var children = childrenRefs.split(',')
var sum = 0
children.forEach( function(child) {
sum += ss.getActiveSheet().getRange(child).getValue()
})
return sum / children.length
}
The following GIF shows the buggy behaviour. Note that I commented out the unhighlightChildren
method call in order to show the buggy behaviour. If I leave it in you wouldn't see the highlight, since after 4 seconds the highlight is triggered but is immediately followed by unhighlight, which makes it appear as if neither method is called (which is not true):