You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用onSelectionChange(e)避免隐藏行时出现无限循环?

解决无限循环的方案

你可以通过添加状态标记或时间间隔判断,区分用户手动点击和系统自动切换选中的场景,从而只隐藏一行:

方法一:使用脚本属性存储状态

function onSelectionChange(e) {
  const props = PropertiesService.getScriptProperties();
  const isProcessing = props.getProperty('isProcessing');
  
  if (isProcessing === 'true') {
    props.deleteProperty('isProcessing');
    return;
  }
  
  const sheet = e.range.getSheet();
  const activeRow = e.range.getRow();
  
  props.setProperty('isProcessing', 'true');
  sheet.hideRows(activeRow);
}

原理:用户手动点击时触发脚本,设置标记后隐藏行;行隐藏后系统自动选中下一行,再次触发脚本时检测到标记,清除标记并跳过执行,避免循环。

方法二:通过时间间隔判断

let lastRunTime = 0;

function onSelectionChange(e) {
  const now = Date.now();
  if (now - lastRunTime < 100) {
    lastRunTime = now;
    return;
  }
  
  const sheet = e.range.getSheet();
  sheet.hideRows(e.range.getRow());
  lastRunTime = now;
}

原理:系统自动切换选中的触发间隔极短(小于100毫秒),用户手动点击的间隔则更长,通过这个阈值过滤掉系统触发的重复执行。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:15:46