Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery setInterval() not working

I'm trying to create a kind of slideshow.

The problem:

function slides(x) {
      $("#irack").stop().animate({"left": x}, 20);
 };
setInterval(slides(-30),300);

This code only moves the div to the left 1 time.

Why doesn't it move the div every 300ms ?

like image 954
XCS Avatar asked Dec 29 '10 16:12

XCS


People also ask

Is setInterval deprecated?

We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);

How do you run setInterval immediately?

Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.

Does setInterval repeat?

The setInterval() method repeats a given function at every given time-interval. window. setInterval(function, milliseconds);

How many times does setInterval run?

setInterval will run the function sendMessage every second (1000 ms).


2 Answers

You need to wrap the code to run at intervals in a function:

function slides(x) {
      $("#irack").stop().animate({"left": x}, 20);
};
setInterval(function() {
    slides(-30);
}, 300);

Did you really mean setInterval? That will keep happening, every 300ms or so. If you want it just to happen once, use setTimeout instead.

Update: If you want to cancel the interval later, you'll need to save the handle to a variable:

// Somewhere appropriate, have a variable for the handle
var handle = 0; // 0 = not running

...

// Starting:
handle = setInterval(...);

...

// Stopping:
if (handle != 0) {
    clearInterval(handle);
}
handle = 0;

Note the use of 0 for the handle when it's not set. 0 is an invalid return value from setInterval, so you can rely on it. (You can use undefined or null if you like as well, just be sure to check for them.)

like image 108
T.J. Crowder Avatar answered Sep 20 '22 12:09

T.J. Crowder


In you call to setInterval the slides method is being called inline change the call to as below:

setInterval(function(){slides(-30);},300);
like image 22
Chandu Avatar answered Sep 22 '22 12:09

Chandu