开发者

Problems with setInterval

I am just trying to implement the most basic example of setInterval with jQuery and am having problems. What's wrong here?

It says function rotate is not defined.

$(document).ready(function() {
    var speed = 5000;
    var run = setInterval("rotate()", speed);

    funct开发者_运维问答ion rotate() {
        alert ('rotate');
    }
});


Do this instead:

$(document).ready(function() {
    var speed = 5000;

    function rotate() {
        alert ('rotate');
    }

    var run = setInterval(rotate, speed);
});

You could also simply do this:

$(function() {
    var speed = 5000;

    var run = setInterval(function() {
        alert ('rotate');
    }, speed);
});

You should declare run outside the ready event handler if you wish to be able to clear the interval later though, since it will go out of scope otherwise.


You are passing setInterval a string to eval. This is:

  • Hard to debug
  • Inefficient
  • Ugly
  • executed in a different scope

The function is limited in scope to the function it is defined inside.

Pass the function directly instead

    var run = setInterval(rotate, speed);


omit the parenthesis and quotes around rotate in your setInterval call. You are giving it the function itself, not the name. It shouldn't matter the order that they go in.


That's effectively eval-ing rotate in (what I believe is) its own context. Change it to

var run = setInterval(rotate, speed);

and it should be fine.


or even put the rotate function outside the ready function.


this works

$(document).ready(function() {
    function rotate() {
        alert ('rotate');
    }
    var speed = 5000;
    var run = setInterval(function() { rotate() }, speed);

});


$(function() {
   var speed = 5000;
   var rotate = function() {
      alert("rotate");
   };

   window.setInterval(rotate, speed);
});


You need to define rotate in the global scope.

$(document).ready(function() {
    window.rotate = function() {
        alert ('rotate');
    }
    var speed = 5000;
    var run = setInterval("rotate()", speed);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜