0

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?

James
  • 5,137
  • 5
  • 40
  • 80

1 Answers1

0

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.

Community
  • 1
  • 1
ximi
  • 596
  • 5
  • 17
  • `setTimeout` can't re-call a function if `animate` is running right? – James Jul 08 '11 at 15:20
  • This seems a much cleaner way of doing things. Cheers! – James Jul 08 '11 at 15:26
  • setTimeout can recall the function if animate is still running. If you want call the function again after the animation has completed use the callback function animate provides you with. – ximi Jul 11 '11 at 09:41