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

如何为以下jQuery循环动画代码设置setTimeout延迟?

为循环动画添加setTimeout间隔的解决方案

嘿,这个需求很容易实现!你只需要在动画完成的回调函数中,把下一次animateM()的调用包裹进setTimeout里,就能控制两次动画之间的间隔了。

修改后的完整代码

$(document).ready(function(){ 
  animateM(); 
}); 

function newPosition(){ 
  var h = $(window).height() - 50; 
  var w = $(window).width() - 50; 
  var nh = Math.floor(Math.random() * h); 
  var nw = Math.floor(Math.random() * w); 
  return [nh,nw]; 
} 

function animateM(){ 
  var newq = newPosition(); 
  $('.animateM').animate({ 
    top: newq[0], 
    left: newq[1] 
  }, function(){ 
    // 这里就是关键:用setTimeout延迟触发下一次动画
    // 第二个参数是间隔时间,单位是毫秒,这里设置的是1000ms=1秒,你可以按需调整
    setTimeout(animateM, 1000); 
  }); 
};

关键说明

  • 原代码中动画完成后立即调用animateM(),现在我们把这个调用放进setTimeout,通过第二个参数指定延迟时间(比如示例中的1000毫秒)。
  • 你可以根据需求修改setTimeout的第二个参数,比如改成2000就是间隔2秒,数值越大间隔越长。
  • 这样修改后,元素每次完成移动动画后,会等待你设置的时间,再开始下一次随机位置的动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:39:12