setTimeout runs only once?

前端 未结 8 1623
醉酒成梦
醉酒成梦 2020-12-10 10:43
function slide()
{
    if($(\'.current\').is(\':last-child\')){
        $(\'.current\').removeClass(\'.current\');
        $(\'#imgholder\').first().addClass(\'.curr         


        
相关标签:
8条回答
  • 2020-12-10 10:51

    You are looking for setInterval

    See: https://developer.mozilla.org/en/window.setInterval

    0 讨论(0)
  • 2020-12-10 10:53

    That's because setTimeout() is supposed to run only once. In order to fire an event on set intervals user setInterval().

    0 讨论(0)
  • 2020-12-10 10:57

    You only call it once, so it'll only execute once.

    Perhaps you're thinking of "setInterval()".

    When you call it, by the way, just pass the name of the function and not a string:

    setInterval(slide, 3000);
    
    0 讨论(0)
  • 2020-12-10 10:58

    setTimeout should only run once. You're looking for setInterval.

    var loop_handle = setInterval(slide, 3000);
    

    Also, the second argument should be a number, not a string. When the function call doesn't require any arguments, it's better to reference to the function instead of using a string. A string would be converted to a function. This function will be executed within the scope of the window.

      setInterval("slide()", 3000);
    //becomes
      setInterval(Function("slide();"), 3000);
    
    0 讨论(0)
  • 2020-12-10 11:02

    Yes, setTimeout only runs once. You need setInterval.

    0 讨论(0)
  • 2020-12-10 11:02

    use setTimeout with recursion (endless loop)

    If you want to keep the exact space between each function call use setTimeout instead setInterval. setInterval can overlap at some point and this is often not expected behavior.

    (function test(){
      setTimeout(function(){
        console.log(1);
        testt();
      }, 2000)
    })()
    
    0 讨论(0)
提交回复
热议问题