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

JavaScript实现API报价响应后触发4分钟倒计时的方法

实现方案

核心逻辑调整思路

  • 移除原逻辑中页面加载即自动启动倒计时的逻辑,页面初始化仅展示预设的4分钟静态值
  • 新增全局状态存储倒计时任务实例,避免重复触发报价时多个计时任务叠加导致时间异常
  • 调整计时器启动时机:仅在报价接口成功返回结果、完成兑换金额渲染后才触发倒计时启动
  • 每次触发新的报价请求时,自动重置倒计时为4分钟重新计数,倒计时归零时自动停止,不会自动循环重置

完整修改后代码

HTML结构(无需调整,保持原有代码即可)

<section>
  <h6>Timer</h6><div><span id="time">04:00</span></div>
</section>

JS逻辑代码

// 全局状态存储倒计时实例、默认时长、显示元素引用
let countdownInterval = null;
const DEFAULT_TIMER_DURATION = 60 * 4;
const timeDisplay = document.querySelector('#time');

/**
 * 渲染时间展示
 * @param {number} totalSeconds 剩余总秒数
 */
function renderTimeDisplay(totalSeconds) {
  const minutes = parseInt(totalSeconds / 60, 10);
  const seconds = parseInt(totalSeconds % 60, 10);
  timeDisplay.textContent = `${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
}

/**
 * 启动/重置倒计时
 */
function startTimer() {
  // 启动前先清除已存在的倒计时任务,避免多任务冲突
  if (countdownInterval) {
    clearInterval(countdownInterval);
  }

  let remainingSeconds = DEFAULT_TIMER_DURATION;
  // 启动时立刻渲染初始4分钟值,避免第一秒显示延迟
  renderTimeDisplay(remainingSeconds);

  countdownInterval = setInterval(() => {
    remainingSeconds--;
    renderTimeDisplay(remainingSeconds);

    // 倒计时归零时清除任务,停止计数
    if (remainingSeconds <= 0) {
      clearInterval(countdownInterval);
      countdownInterval = null;
    }
  }, 1000);
}

window.onload = function () {
  // 页面初始化仅渲染默认04:00,不启动计时
  renderTimeDisplay(DEFAULT_TIMER_DURATION);
};

async function getQuote() {
  if (
    !currentTrade.from ||
    !currentTrade.to ||
    !document.getElementById("from").value
  )
    return;

  let amount = Number(
    document.getElementById("from").value *
      10 ** currentTrade.from.decimals
  );

  const quote = await Plug.quote({
    network: "repl",
    fromAddress: currentTrade.from.address,
    toAddress: currentTrade.to.address,
    amount: amount,
  });
  console.log(quote);
  document.getElementById("to").value =
    quote.toAmount / 10 ** quote.to.decimals;

  // 报价成功返回后启动/重置倒计时
  startTimer();
}

交互验证点

  • 页面刚加载、未触发报价请求时,计时器始终显示04:00,不会自动走字
  • 每次发起报价请求、拿到有效返回结果后,计时器立刻重置为04:00开始倒计时
  • 倒计时走到00:00后自动停止,不会自动循环重置
  • 多次连续触发报价请求时,不会出现时间跳变、多计时器同时运行的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:51:20