How to delay in JavaScript
the .defer(5000)
is causing a too much recursion
error in JavaScript. How do I delay the execution by 5 seconds?
rotate: function () {
if (!paused) {
this.show(counter);
counter = counter + 1;
if (counter =开发者_如何学Python== Spire.Rotator.data.items.length) {
counter = 0;
}
Spire.Rotator.rotate().defer(5000);
//$.proxy(Spire.Rotator.rotate, Spire.Rotator).defer(delay);
}
}
This entire line:
Spire.Rotator.rotate().defer(5000);
is wrong. Because of the parentheses just after rotate
, your function is immediately calling itself over and over again (infinite recursion). Removing the parentheses will fix that problem, but the code will probably not work. To fix the code, use the browser's window.setTimeout
method, which accepts a function and a delay (in milliseconds) as two arguments:
setTimeout(function() {
Spire.Rotator.rotate();
}, 5000);
Why not just setTimeout(Spire.Rotator.rotate, 5000);
? The reason is that this
in that function would be window
rather than Spire.Rotator
. (There's plenty of information on the Internet about this.) Why not setTimeout("Spire.Rotator.rotate()", 5000);
? That's a quite dated (deprecated) way to use the method that suffers from the same pitfalls of eval, a function that some JavaScript programmers including Douglas Crockford recommend not using.
Simply substitute this:
Spire.Rotator.rotate().defer(5000);
With this:
setTimeout(Spire.Rotator.rotate, 5000);
setTimeout()
is javascript's native way of executing some Javascript code after a specified amount of time.
Actually, in your code, defer() never gets called. Assuming the rotate method you're defining is for the Spire.Rotator object what happens is:
rotate() calls rotate() calls rotate() calls rotate() .... [to infinity]
After infinity
number of calls the return value of the infinitieth
call will then call the defer method. But you have to wait for infinity
calls to happen which takes eternity
seconds to complete.
What you need is setTimeout().
精彩评论