开发者

Function not defined in setInterval

Hallo, I've got something like this:

$(document).ready(function(){

 $("#all").height($(window).height()-60);

$('a').bind({
  mouseover:function(){
   $(this).stop().animate({opacity:0.8},500);
 },
 mouseout:function(){
   $(this).stop().animate({opacity:1},500);
 },
   click:function(){
 }
});


// CLOUDS SCROLL 

 function cloudScr开发者_运维百科oll(){
     var current=parseFloat($('#clouds').css('left'));
     current += 1;
     $('#clouds').css("left",current);
 }

var init = setInterval('cloudScroll()', 270);

});

Seems to be quite easy but anyway it returns: cloudScroll is not defined.

Why?


Try passing the function directly, using a string is quite obsolete:

var init = setInterval(cloudScroll, 270);


setInterval is executed in the global namespace, but your cloud scroll function is defined in the anonymous document.ready function.

It should fix your problem and it's also better form to pass function references to setInterval rather than strings (which ultimately get evaled, which is worse for performance):

setInterval(function (){ cloudsScroll() }, 270);

You could also put the cloudScroll definition in the interval function.


Give this a try:

var init = setInterval(cloudScroll, 270); 

... and if you want to pass arguments:

setInterval(scrollCloud, 250, clouds2);

EDIT Partrick mentioned that IE doesn't support passing arguments in the above manner. Surprised I didn't now that. Anyway that makes mqsoh's use of an anonymous function relevant. Because you can run a given function with arguments like so:

setInterval(function(){
  scrollCloud(clouds2);
}, 250);


If you pass the function reference, rather than a string, then it will work:

var init = setInterval(cloudScroll, 270);

Just to show it working: http://jsfiddle.net/jonathon/T45Nx/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜