jquery setInterval()不工作 [英] Jquery setInterval() not working

查看:97
本文介绍了jquery setInterval()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



问题:

 函数幻灯片(x){
$(#irack)。stop()。animate({left:x},20);
};
setInterval(幻灯片(-30),300);

此代码仅将div移动到左侧1次。



为什么它不会每隔300ms移动一次div?

解决方案

您需要打包代码才能运行在函数中每隔一段时间:

 函数幻灯片(x){
$(#irack)。stop ).animate({left:x},20);
};
setInterval(function(){
slides(-30);
},300);

您真的指 的setInterval ?这将继续发生,每隔300毫秒左右。如果您希望只发生一次,请使用 setTimeout 代替。



更新:如果您想稍后取消时间间隔,则需要将句柄一个变量:

  //在适当的地方,为句柄赋予一个变量
var handle = 0; // 0 =没有运行

...

//开始:
handle = setInterval(...);



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

请注意使用 0 当它没有设置。 0 是来自 setInterval 的无效返回值,因此您可以依赖它。 (如果你喜欢,你可以使用 undefined null ,只要一定要检查它们。) p>

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 ?

解决方案

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

这篇关于jquery setInterval()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆