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

LocalStorage问题:2分钟内多次点击无法重复显示警告控制台消息

问题解决:2分钟内重复运行代码持续输出警告

需求明确:

  • 首次运行代码时,输出默认控制台消息
  • 2分钟内任意次数运行代码,都要输出Warning: Clicked within 2 minutes!
  • 超过2分钟后运行,恢复显示默认消息

原代码的问题在于用warningLogged标记了警告是否已输出,导致2分钟内只有第一次重复运行会触发警告,后续运行不再输出。要实现需求,只需要移除这个多余的标记逻辑,直接基于时间差判断输出内容即可。

修改后的代码:

const lastClickedTime = localStorage.getItem('lastClickedTime');
const currentTime = new Date();
const timeDiff = currentTime.getTime() - Number(lastClickedTime);

if (lastClickedTime && timeDiff <= 120000) {
  console.log('Warning: Clicked within 2 minutes!');
} else {
  console.log('Default message:', currentTime);
}

localStorage.setItem('lastClickedTime', String(currentTime.getTime()));

修改说明:

  • 移除了所有和warningLogged相关的代码,不再跟踪警告是否已输出
  • 计算时间差并直接判断:只要上次运行时间存在且间隔不超过2分钟,就输出警告
  • 超过2分钟或首次运行时,输出默认消息
  • 每次运行都会更新lastClickedTime为当前时间,确保下次判断的基准正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:27:39