Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
781 views
in Technique[技术] by (71.8m points)

function - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...