JQuery, setTimeout not working

前端 未结 4 457
挽巷
挽巷 2020-11-30 23:28

I\'m still new to JQuery, on the way to getting my ajax example to work i got stalled with setTimeout. I have broken it down to to where it should add \".\" to the div eve

相关标签:
4条回答
  • 2020-12-01 00:00

    You've got a couple of issues here.

    Firstly, you're defining your code within an anonymous function. This construct:

    (function() {
      ...
    )();
    

    does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

    You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

    (function() {
      $(document).ready(function() {update();});
    
      function update() { 
        $("#board").append(".");
        setTimeout(update, 1000);     }
      }
    )();
    

    because the function pointer update is within scope of that block.

    But like I said, there is no need for the anonymous function so you can rewrite it like this:

    $(document).ready(function() {update();});
    
    function update() { 
      $("#board").append(".");
      setTimeout(update, 1000);     }
    }
    

    or

    $(document).ready(function() {update();});
    
    function update() { 
      $("#board").append(".");
      setTimeout('update()', 1000);     }
    }
    

    and both of these work. The second works because the update() within the code block is within scope now.

    I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

    $(function() {
      setInterval(update, 1000);
    });
    
    function update() {
      $("#board").append(".");
    }
    

    Hope that clears that up.

    0 讨论(0)
  • 2020-12-01 00:08

    This accomplishes the same thing but is much simpler:

    $(document).ready(function() {  
       $("#board").delay(1000).append(".");
    });
    

    You can chain a delay before almost any jQuery method.

    0 讨论(0)
  • 2020-12-01 00:12

    SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.

    0 讨论(0)
  • 2020-12-01 00:13
    setInterval(function() {
        $('#board').append('.');
    }, 1000);
    

    You can use clearInterval if you wanted to stop it at one point.

    0 讨论(0)
提交回复
热议问题