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

JS如何使用IF条件切换运行代码且不打乱循环动画效果

JS时钟按时段切换动画解决方案

核心逻辑是单独存储当前生效的时段状态、动画定时器ID和帧索引,仅当时段状态发生变化时才重置动画,避免重复运行导致的帧错乱。

// 预先定义两个时段的动画数组,避免重复声明
const dayHat = ['1','2','3','4']
const nightHat = ['A','B','C','D']

// 存储全局状态:当前生效模式、动画定时器ID、当前帧索引
let currentMode = null
let animationTimer = null
let frameIndex = -1

// 抽离公共的动画渲染逻辑,避免重复代码
function renderFrame(hatArr) {
  frameIndex = (frameIndex + 1) % hatArr.length
  document.querySelector(".main").textContent = hatArr[frameIndex]
  animationTimer = setTimeout(() => renderFrame(hatArr), 1000)
}

// 时间检查逻辑,仅模式变化时重启动画
function checkTimeAndSwitch() {
  const now = new Date()
  const isNight = now.getHours() > 20
  const targetMode = isNight ? 'night' : 'day'

  // 模式未变化直接返回,不做任何操作
  if (targetMode === currentMode) return

  // 模式变化时,先清除旧的动画定时器,重置帧索引
  if (animationTimer) clearTimeout(animationTimer)
  frameIndex = -1
  currentMode = targetMode

  // 启动对应模式的动画
  const targetHat = isNight ? nightHat : dayHat
  renderFrame(targetHat)
}

// 初始化执行一次
checkTimeAndSwitch()
// 定时检查时间,这里设置为每30秒检查一次,可根据需求修改间隔(单位毫秒)
setInterval(checkTimeAndSwitch, 30 * 1000)

关键说明

  • 之前的异常是因为你把动画启动逻辑直接放到了定时执行的代码里,每次执行都会启动新的动画循环,多个定时器同时运行才会导致帧序列混乱。现在定时任务只执行时间检查逻辑,不会干涉正常运行的动画。
  • 所有公共状态单独存储,切换模式时才会重置帧索引,你如果需要切换时不重置帧,直接删掉frameIndex = -1这行即可。
  • 检查间隔可以自行调整,比如要减少性能消耗可以改成60000(1分钟),对精度要求高也可以改成10000(10秒)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:24:04