jeffreynolte
jeffreynolte

Reputation: 3779

Better way than setInterval?

I have the current function below, but feel like there is a much better way to write the same thing. I am looking for some insight on the most optimized way to write the same function below and why.

Note this is all inside of $(function(){});

m = function(){
  $("#id").animate({marginRight : 0}, 'slow', function(){
       $("#id").animate({marginRight : "15px"}, 'slow');
     })
} 
 setInterval(m, 700)      

Upvotes: 0

Views: 690

Answers (3)

Kevin B
Kevin B

Reputation: 95017

(function m(){
    $("#id").animate({marginRight : 0}, 'slow', function(){
        $(this).animate({marginRight : "15px"}, 'slow',function(){
            setTimeout(m,700);
        });
     });
})();

EDIT:

it uses setTimeout, however, setTimeout is a better solution than setInterval because it will only queue a new one if the previous one is complete. This will help prevent issues with the RAF that jquery 1.6 currently makes use of.

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69915

You can improvise to use this inside the first animation callback instead of finding it again. Other than that I dont think any further improvement can be done here.

m = function(){
  $("#id").animate({marginRight : 0}, 'slow', function(){
       $(this).animate({marginRight : "15px"}, 'slow');
     })
} 
 setInterval(m, 700); 

Upvotes: 1

Maz
Maz

Reputation: 3375

m = function(){
  $("#id").animate({marginRight : 0}, 'slow', function(){
       $("#id").animate({marginRight : "15px"}, 'slow',m);
     });
} 
m();

It seems, based on what you are doing that you want to toggle an element's motion over time. You can just set the original function m() as a callback to be executed when the second, inner animation is done.

Upvotes: 3

Related Questions