user701510
user701510

Reputation: 5763

function in setInterval() executes without delay

I am in the process of making a jquery application to hide an image after a specified interval of time by using setInterval(). The problem is that the hide image function executes immediately without delay.

$(document).ready(function() {

  setInterval(change(), 99999999);

  function change() {
    $('#slideshow img').eq(0).removeClass('show');

  }

});

I am testing it in jsfiddle.

Upvotes: 5

Views: 5407

Answers (4)

aparker42
aparker42

Reputation: 996

Where you have setInterval(change(), 99999999); you end up calling the change() function immediately and passing the return value of it to the setInterval() function. You need delay the execution of change() by wrapping it in a function.

setInterval(function() { change() }, 9999999);

Or you can delay it by passing setInterval() just the function itself without calling it.

setInterval(change, 9999999);

Either works. I personally find the first one a bit clearer about the intent than the second.

Upvotes: 4

Esailija
Esailija

Reputation: 140230

http://jsfiddle.net/wWHux/3/

You called the function immediately instead of passing it to setInterval.

setInterval( change, 1500 ) - passes function change to setInterval

setInterval( change(), 1500 ) - calls the function change and passes the result (undefined) to setInterval

Upvotes: 11

xdazz
xdazz

Reputation: 160843

Change setInterval(change(), 99999999); to setInterval(change, 99999999);

And 99999999 means 99999999 milliseconds as you known.

Upvotes: 1

freakish
freakish

Reputation: 56477

You have setInterval(change(), 99999999); and it should be setInterval(change, 99999999);. See the documentation of setInterval/setTimeout why. :)

Common mistake, happens to me all the time. :)

Upvotes: 1

Related Questions