开发者

Improve JavaScript setInterval code

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 a开发者_StackOverflow社区nimation.

I'm sure doing it this way will have a lot of speed issues and whatever else.

Can it be improved?


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.

var tidalWave = function() {
   $("#waves-1").animate({path: new FirstWave}, 10999, "linear");
   setTimeout(tidalWave, 500);
};

setTimeout(tidalWave, 500);

Now you could also use $(document).ready instead of the initial timeout.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜