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

如何为Google Script函数添加15分钟冷却计时器

实现Cancel函数的15分钟冷却机制

核心思路

利用Google Apps Script内置的PropertiesService存储冷却截止时间,每次调用Cancel函数时先检查当前时间是否在冷却期内,若在则直接终止函数;若通过验证则正常执行,执行到正确密码分支时更新冷却截止时间。

修改后的完整代码

function Cancel() {
  // 冷却配置
  const COOLDOWN_MINUTES = 15;
  const COOLDOWN_KEY = 'cancel_cooldown_end';
  const userProps = PropertiesService.getUserProperties();
  
  // 检查冷却状态
  const cooldownEndStr = userProps.getProperty(COOLDOWN_KEY);
  if (cooldownEndStr) {
    const now = Date.now();
    const cooldownEnd = parseInt(cooldownEndStr);
    if (now < cooldownEnd) {
      const remaining = Math.ceil((cooldownEnd - now) / (1000 * 60));
      SpreadsheetApp.getUi().alert(`请等待 ${remaining} 分钟后再操作`);
      return;
    }
  }

  var SS = SpreadsheetApp.getActiveSpreadsheet();
  var ui = SpreadsheetApp.getUi();

  // first prompt
  var presult = ui.prompt(
    "Please Enter the Password!",
    ui.ButtonSet.OK_CANCEL);

  var password = "Money2022";
  var pbutton = presult.getSelectedButton();
  var ptext = presult.getResponseText();

  // User clicked "OK" on first prompt
  if (pbutton == ui.Button.CANCEL) {
    ui.alert('Wrong Answer Buddy!');
    SpreadsheetApp.getActive().getSheetByName('2022').hideSheet();
  } else if (pbutton == ui.Button.CLOSE) {
    ui.alert('Wrong Answer Buddy!');
    SpreadsheetApp.getActive().getSheetByName('2022').hideSheet();
  } else if (ptext != password) {
    Password();   
  } else {
    // 设置冷却时间
    const newCooldownEnd = Date.now() + COOLDOWN_MINUTES * 60 * 1000;
    userProps.setProperty(COOLDOWN_KEY, newCooldownEnd.toString());
    
    // 这里添加密码正确后的业务逻辑(示例:显示工作表)
    SpreadsheetApp.getActive().getSheetByName('2022').showSheet();
    ui.alert('密码正确!');
  }
}

function Password() {
  var SS = SpreadsheetApp.getActiveSpreadsheet();
  var ui = SpreadsheetApp.getUi();
  var response = ui.alert("Wrong Answer Buddy!",
      ui.ButtonSet.OK_CANCEL);

  if (response == ui.Button.CANCEL) {
    ui.alert("BYE BYE!");
    SpreadsheetApp.getActive().getSheetByName('2022').hideSheet();
  } else if (response == ui.Button.CLOSE) {
    ui.alert("BYE BYE!");
    SpreadsheetApp.getActive().getSheetByName('2022').hideSheet();
  } else {
    Cancel();
  }
}

关键说明

  • PropertiesService.getUserProperties(): 存储当前用户的冷却时间,不同用户之间互不影响;如果需要全局冷却(所有用户共享),可替换为PropertiesService.getScriptProperties()。
  • 冷却时间计算: 使用Date.now()获取当前时间戳(毫秒),加上15分钟对应的毫秒数(15601000)得到冷却截止时间。
  • 冷却检查: 函数启动时先读取存储的截止时间,若当前时间未超过则提示剩余时间并终止执行。
  • 状态持久化: PropertiesService的数据会永久保存,除非主动清除(可通过userProps.deleteProperty(COOLDOWN_KEY)手动移除冷却)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:20:28