请求开发Google Spreadsheet竞赛用多时长切换倒计时计时器(带启停按钮)
Google Sheets 竞赛场景倒计时计时器实现方案
实现思路
借助Google Apps Script处理计时逻辑,结合Sheet单元格完成时长设置与倒计时显示,通过自定义按钮绑定脚本实现启停控制,支持预设时长快速切换和自定义时长输入。
步骤1:编写Apps Script代码
- 打开目标Google Spreadsheet,点击顶部菜单栏「扩展程序」→「Apps Script」进入脚本编辑器。
- 清空默认代码,粘贴以下脚本:
let timerId = null; let remainingSeconds = 0; // 启动倒计时 function startTimer() { // 先停止已有计时器,避免冲突 stopTimer(); const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 读取A1预设时长(分钟),无值则读取B1自定义时长 const presetMinutes = activeSheet.getRange("A1").getValue(); const customMinutes = activeSheet.getRange("B1").getValue(); const totalMinutes = presetMinutes || customMinutes; if (!totalMinutes || totalMinutes <= 0) { SpreadsheetApp.getUi().alert("请设置有效的计时时长"); return; } remainingSeconds = totalMinutes * 60; updateDisplay(); // 每秒更新一次倒计时 timerId = setInterval(() => { remainingSeconds--; if (remainingSeconds <= 0) { stopTimer(); SpreadsheetApp.getUi().alert("时间到!"); activeSheet.getRange("C1").setValue("00:00"); return; } updateDisplay(); }, 1000); } // 停止倒计时 function stopTimer() { if (timerId) { clearInterval(timerId); timerId = null; } } // 更新倒计时显示 function updateDisplay() { const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const minutes = Math.floor(remainingSeconds / 60); const seconds = remainingSeconds % 60; // 格式化分秒为两位数字 const displayText = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`; activeSheet.getRange("C1").setValue(displayText); }
- 点击脚本编辑器顶部「保存」,给项目命名(比如“竞赛倒计时器”)。
步骤2:设置Sheet界面
1. 时长设置区域
- 预设时长:选中A1单元格,点击「数据」→「数据验证」,在面板中:
- 条件选择「列表项」
- 输入框填写
1,2,4,5(对应1/2/4/5分钟) - 勾选「显示下拉箭头」后保存
- 自定义时长:直接在B1单元格输入任意正整数(单位:分钟),若A1有值则优先使用预设时长。
2. 倒计时显示区域
选中C1单元格,设置大号字体(比如24号)、居中对齐,让倒计时更醒目。
3. 添加启停按钮
- 点击「插入」→「绘图」,选择矩形形状,添加文字「Start」,调整样式后保存。
- 右键该绘图,选择「分配脚本」,输入
startTimer(不带括号)确定。 - 重复上述步骤添加「Stop」按钮,分配脚本
stopTimer。
功能使用说明
- 切换时长:在A1下拉菜单选预设时长,或在B1输入自定义时长,点击「Start」启动对应倒计时。
- 启停控制:点击「Start」启动计时,点击「Stop」可随时暂停/停止。
- 到期提醒:倒计时结束时弹出系统提示框,C1同步显示「00:00」。
注意事项
- 首次运行脚本会触发权限授权,按指引完成即可(需登录Google账号)。
- 切换时长前建议先点击「Stop」停止当前计时,避免逻辑冲突。
内容的提问来源于stack exchange,提问作者Gabriel Sousa
相关产品推荐
相关产品推荐

