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

如何在现有JavaScript语录脚本中插入60秒自动刷新定时器?

实现语录60秒自动切换的修改方案

直接用下面修改好的代码替换原脚本即可:

const generateQuote = function() {
  const quotes = [
    {
      quote: "不要怜悯死者,哈利。怜悯活人,尤其是那些没有爱的人。",
      author: "阿不思·邓布利多"
    },
    {
      quote: "爱不可能被制造或模仿。",
      author: "霍拉斯·斯拉格霍恩"
    },
    {
      quote: "与众不同不是坏事。这意味着你有勇气做自己。",
      author: "卢娜·洛夫古德"
    }
  ];

  let arrayIndex = Math.floor(Math.random() * quotes.length);
  document.getElementById("quotes").innerHTML = quotes[arrayIndex].quote;
  document.getElementById("author").innerHTML = quotes[arrayIndex].author;
}

// 存储定时器实例,用于后续重置
let quoteTimer;

window.onload = function() {
  // 页面加载先展示一条语录
  generateQuote();
  
  // 启动60秒自动切换定时器
  quoteTimer = setInterval(generateQuote, 60000);
  
  // 手动点击刷新时,同步重置定时器
  document.getElementById("generate").addEventListener('click', function() {
    generateQuote();
    clearInterval(quoteTimer);
    quoteTimer = setInterval(generateQuote, 60000);
  });
}

核心修改点:

  • 移除了原数组里的空对象,避免随机到空内容导致页面显示异常。
  • 新增quoteTimer变量管理定时器实例,解决手动刷新后不久就自动切换的问题。
  • 用setInterval实现每60秒自动调用语录生成函数,同时在手动点击时重置定时器,保证从点击时刻重新计算60秒。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 20:56:03