简体   繁体   English

SetTimeout延迟在jquery幻灯片中没有按预期工作

[英]SetTimeout delay not working as expected in jquery slide

这是我的代码.... http://jsfiddle.net/KQ8gW/在这个我已经将我的setTimeout放置到1分钟,但在此之前调用该函数。为什么它是这样????

You are calling the function immediately, not passing a reference to the function and you are repeatedly setting the interval. 您正在立即调用该函数,而不是传递对该函数的引用,并且您正在重复设置该间隔。 So, what you're passing to setInterval() is the return value from executing Slide(c,n) , not a function that will be called later. 因此,您传递给setInterval()是执行Slide(c,n)的返回值,而不是稍后将调用的函数。 Thus it gets called immediately and only once. 因此它立即被调用,只被调用一次。

To fix it, change this: 要修复它,请更改:

setInterval(Slide(c,n),60000);

to this: 对此:

setTimeout(function() {Slide(c,n)},60000);

If this were my code, I wouldn't even use a timer - I'd use the animation completion function like this: 如果这是我的代码,我甚至不会使用计时器 - 我会使用这样的动画完成功能:

var n = $("#slideShow div img").length;
var c = 0;
Slide(c,n);

function Slide(c,n){
    c = ++c % n;
    $("#slideShow div").animate(
        {left:-500*c}, 
        3000, 
        function() {Slide(c,n)}
    );
}​

Working Demo: http://jsfiddle.net/jfriend00/nykd3/ 工作演示: http//jsfiddle.net/jfriend00/nykd3/

You have set an interval, not a timeout. 您已设置间隔,而不是超时。 Try using setTimeout(function, time) 尝试使用setTimeout(function, time)

You are calling an interval inside an interval inside an interval.... etc. 你在一个间隔内的间隔内调用间隔....等。

You run the function regularly every minute, and everytime the function runs you set a new interval, looping until infinty and beyond. 您每分钟都会定期运行该功能,并且每次运行该功能时,您都会设置一个新的间隔,循环直到无穷无尽。

Place the interval outside the function, and call it with a function to avoid eval'ing, like so: 将间隔放在函数外部,并使用函数调用它以避免评估,如下所示:

var n = $("#slideShow div img").length, c = 0;

Slide(c, n);
setInterval(function() { Slide(c, n); }, 60000);

function Slide(c, n) {
    c = ++c % n;
    $("#slideShow div").animate({
        left: -500 * c
    }, 7000);
}​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM