开发者

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({marg开发者_JAVA技巧inRight : 0}, 'slow', function(){
       $("#id").animate({marginRight : "15px"}, 'slow');
     })
} 
 setInterval(m, 700)      


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.


(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.


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); 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜