iJade
iJade

Reputation: 23811

SetTimeout delay not working as expected in jquery slide

Here is my code.... http://jsfiddle.net/KQ8gW/ In this i have placed my setTimeout to 1 min but the function is called much before that.Why is it so????

Upvotes: 0

Views: 343

Answers (3)

jfriend00
jfriend00

Reputation: 708056

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

Upvotes: 2

adeneo
adeneo

Reputation: 318342

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);
}​

Upvotes: 0

Amberlamps
Amberlamps

Reputation: 40498

You have set an interval, not a timeout. Try using setTimeout(function, time)

Upvotes: 0

Related Questions