为什么在该工具之前和之后的方法之前执行此Utilities.sleep?

时间:2019-03-25 08:47:49

标签: google-apps-script google-sheets wait

对于使用Utilities.sleep()调用的Google表格,我有以下代码。

有问题的是,highlightChildren()unhighlightChildren()都是在Utilities.sleep()调用后之后执行的,我不知道为什么。

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
}

以下GIF显示了越野车的行为。请注意,我注释了unhighlightChildren方法调用,以显示错误的行为。如果我将其保留在里面,您将看不到高光,因为高光会在4秒钟后触发,但随后会立即取消突出显示,这使其看起来好像都没有调用任何方法(不正确):

sleep before children highlight/unhighlight

0 个答案:

没有答案