How to perform an action every couple of seconds?

后端 未结 6 1801
终归单人心
终归单人心 2020-12-20 14:25

Can someone quickly and simply explain to me how to perform an action every couple of seconds using

var timeOut = setTimeout(FunctionName, 5000);


        
相关标签:
6条回答
  • 2020-12-20 14:37

    In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.

    <html>
      <head>
        <script type="text/javascript">
          var c = 0;
          var t;
          var timer_is_on = false;
    
          function timedCount() {
            document.getElementById('txt').value = c;
            c = c + 1;
            t = setTimeout(timedCount, 1000);
          }
    
          function doTimer() {
            if (!timer_is_on) {
              timer_is_on = true;
              timedCount();
            }
          }
        </script>
      </head>
      <body>
        <form>
          <input type="button" value="Start count!" onclick="doTimer()">
          <input type="text" id="txt" />
        </form>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-12-20 14:50

    As you asked for a method using setTimeout:

    function doStuff() {
       console.log("hello!");
       setTimeout(doStuff, 5000);
    }
    setTimeout(doStuff, 5000);
    

    But it would probably be better to use setInterval:

    function doStuff() {
       console.log("hello!");
    }
    setInterval(doStuff, 5000);
    
    0 讨论(0)
  • 2020-12-20 14:55

    you can do something like:

    $(document).ready(function () 
            {
    setTimeout(nextNotice, 5000);
    }
    function nextNotice()
    {
    // do stuff 
    setTimeout(nextNotice, 5000);
    }
    
    0 讨论(0)
  • 2020-12-20 14:56

    Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.

    0 讨论(0)
  • 2020-12-20 14:56

    Use setInterval:

    var timeOut = setInterval(nextNotice, 5000);
    
    0 讨论(0)
  • 2020-12-20 15:02
    var myFunction = function() { 
         //Do stuff
         AnotherFunction();
    };
    
    var timeOut = setInterval(myFunction, 2000);
    
    0 讨论(0)
提交回复
热议问题