改进 JavaScript setInterval 代码
我目前有一段 JavaScript,它使用 jQuery animate 来创建水运动效果。
var waves = function() {
(function() {
var FirstWave = function() {
this.css = function(p) {
var s = Math.sin(p*5)
var x = (960 * 2) - (p * 960) + 10
var y = s * 5 + 15
return {backgroundPosition: "-" + x + "px", bottom: "-" + y + "px"}
}
};
var tidalWave = function() {
$("#waves-1").animate({path: new FirstWave}, 10999, "linear");
};
setInterval(tidalWave, 500);
})();
};
waves()
在 $(document).ready()
处理程序内调用。
正如您所看到的,即使动画持续时间不到 11 秒,setInterval
也设置为 500。我这样做是为了确保动画在页面加载时启动,因为仅调用 $.animate() 并不会启动动画。
我确信这样做会带来很多速度问题和其他问题。
可以改进吗?
I currently have this bit of JavaScript which uses jQuery animate to create a water movement effect.
var waves = function() {
(function() {
var FirstWave = function() {
this.css = function(p) {
var s = Math.sin(p*5)
var x = (960 * 2) - (p * 960) + 10
var y = s * 5 + 15
return {backgroundPosition: "-" + x + "px", bottom: "-" + y + "px"}
}
};
var tidalWave = function() {
$("#waves-1").animate({path: new FirstWave}, 10999, "linear");
};
setInterval(tidalWave, 500);
})();
};
waves()
is called inside a $(document).ready()
handler.
As you can see, the setInterval
is set to 500 even though the animation lasts for just under 11 seconds. I did this to ensure that the animation starts on page load, since just calling $.animate()
did not kick off the animation.
I'm sure doing it this way will have a lot of speed issues and whatever else.
Can it be improved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用 setTimeout 而不是 setInterval (有多种优点,请参见此处:setTimeout 还是 setInterval?)因为您希望它重复,所以您应该在 tidalWave 函数中执行另一个 setTimeout ,再次调用 tidalWave 本身。
现在您还可以使用 $(document).ready 而不是初始超时。
You should use setTimeout instead of setInterval (there are various advantages, see here: setTimeout or setInterval?) and because you want it to repeat you should just do another setTimeout within your tidalWave function that invokes tidalWave itself again.
Now you could also use $(document).ready instead of the initial timeout.