setTimeout只运行一次?

时间:2011-10-23 16:24:28

标签: javascript settimeout

function slide()
{
    if($('.current').is(':last-child')){
        $('.current').removeClass('.current');
        $('#imgholder').first().addClass('.current');
        $('#imgholder').animate({left: '3920px'});
    }
    else{
        $nxt=$(".current");
        $(".current").removeClass("current");
        $nxt.next().addClass("current");
        $('#imgholder').animate({left: '-=980'},{duration: 'slow', easing: 'easeOutBounce' });
        }
}
var loop_handle= setTimeout("slide()",'3000');

我已将此代码放在标题部分中,而setTimeout只运行一次。

8 个答案:

答案 0 :(得分:66)

setTimeout只能运行一次。您正在寻找setInterval

var loop_handle = setInterval(slide, 3000);

此外,第二个参数应该是数字,而不是字符串。当函数调用不需要任何参数时,最好引用函数而不是使用字符串。字符串将转换为函数。该功能将在窗口范围内执行。

  setInterval("slide()", 3000);
//becomes
  setInterval(Function("slide();"), 3000);

答案 1 :(得分:5)

你只调用一次,所以它只执行一次。

也许您正在考虑“setInterval()”。

当你调用它时,顺便说一下,只传递函数的名称而不是字符串:

setInterval(slide, 3000);

答案 2 :(得分:4)

您正在寻找setInterval

请参阅:https://developer.mozilla.org/en/window.setInterval

答案 3 :(得分:4)

setTimeout功能只运行一次!如果您想要多次运行它,则应使用setInterval

var loop_handle= setInterval("slide()",'3000');

此外,您可以在setTimeout函数的末尾使用slide()重新设置超时:

var loop_handle;
function slide() {
    if($('.current').is(':last-child')) {
        $('.current').removeClass('.current');
        $('#imgholder').first().addClass('.current');
        $('#imgholder').animate({left: '3920px'});
    }
    else {
        $nxt=$(".current");
        $(".current").removeClass("current");
        $nxt.next().addClass("current");
        $('#imgholder').animate({left: '-=980'},{duration: 'slow', easing: 'easeOutBounce' });
    }
    loop_handle = setTimeout("slide()",'3000');
}
loop_handle = setTimeout("slide()",'3000');

答案 4 :(得分:2)

是的,setTimeout只运行一次。你需要setInterval。

答案 5 :(得分:2)

那是因为setTimeout()应该只运行一次。为了在设定的时间间隔内用户setInterval()

触发事件

答案 6 :(得分:0)

使用setTimeout和递归(无限循环)

如果要保持每个函数调用之间的确切空间,请使用 setTimeout 而不是setInterval。 setInterval 可能会在某个时刻重叠,这通常不是预期的行为。

(function test(){
  setTimeout(function(){
    console.log(1);
    testt();
  }, 2000)
})()

答案 7 :(得分:0)

This problem usually happens when you used setTimeout in recursion loop, for example in ajax callback and when you want to run something out of recursion, you expect setTimeout to work as past. remember to use setInterval in non-recursion functions.