You need to enable JavaScript to run this app. 如何用JavaScript setInterval实现1分钟内自动循环缩放圆形动画
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript setInterval实现1分钟内自动循环缩放圆形动画

核心问题排查
  • 元素引用命名不一致:通过document.querySelector('#circle')获取DOM元素时声明的变量为pulseCircle,后续代码直接使用未定义的circle变量操作类名,触发语法报错导致逻辑完全不执行
  • 定时器参数传递错误:setInterval(pulseCircle(), 5000)写法会立刻执行pulseCircle函数,将函数返回值作为间隔回调传入,而非传入函数本身作为定时器触发逻辑
  • 自动动画逻辑残缺:仅保留了添加.hover放大类的分支,没有对应的移除类名缩回尺寸的反向操作,也没有总运行时长满1分钟后的终止判断
  • 代码结构语法错误:零散的类名操作代码没有包裹进可执行的函数块,存在多余的闭合括号,整体无法正常解析运行
修正后的实现逻辑

动画节奏匹配需求:单轮周期为5s放大至2倍、5s缩回原尺寸,总运行60s后自动终止所有动画逻辑,同时保留原有鼠标悬停触发的缩放效果。

<!-- 基础结构与原有代码保持一致 -->
<div id="circle">Hover</div>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande',
    'Lucida Sans', Arial, sans-serif;
}

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

#circle {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  width: 200px;
  background: slateblue;
  border-radius: 100px;
  font-size: 1.5rem;
  color: #fff;
  cursor: pointer;
  /* 匹配5s缩放过渡的时长要求 */
  transition: cubic-bezier(0.075, 0.82, 0.165, 1) 5s;
}

.hover {
  transform: scale(2);
}
// 统一DOM元素引用命名
const circle = document.querySelector('#circle');
// 记录自动动画的已运行时长
let autoRunDuration = 0;
// 单次切换类名的间隔为5s,对应5s放大、5s缩回的节奏
const PULSE_INTERVAL = 5000;
// 总运行时长60s,达到后清除定时器
const TOTAL_RUN_TIME = 60000;

// 自动切换缩放状态的逻辑
const togglePulseState = () => {
  // 切换.hover类,实现放大/缩回的效果
  circle.classList.toggle('hover');
  autoRunDuration += PULSE_INTERVAL;
  // 达到总时长后终止自动动画
  if (autoRunDuration >= TOTAL_RUN_TIME) {
    clearInterval(autoPulseTimer);
    // 终止后移除所有hover类,回到初始状态
    circle.classList.remove('hover');
  }
}

// 启动自动循环定时器
const autoPulseTimer = setInterval(togglePulseState, PULSE_INTERVAL);

// 保留原有鼠标触发逻辑
circle.addEventListener('mouseenter', () => {
  circle.classList.add('hover')
})

circle.addEventListener('mouseleave', () => {
  circle.classList.remove('hover')
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 12:36:02