Do something every 5 seconds and the code to stop it. (JQuery)

前端 未结 4 1765
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 05:22

How can I repeat a function doSomething() every 5 seconds.

I also need code that will make it stop doing it.

And code to on-the-fly adjust the f

相关标签:
4条回答
  • 2020-12-15 06:12

    setTimeout() will only launch the command once. In this case, setInterval() is your friend.

    var iFrequency = 5000; // expressed in miliseconds
    var myInterval = 0;
    
    // STARTS and Resets the loop if any
    function startLoop() {
        if(myInterval > 0) clearInterval(myInterval);  // stop
        myInterval = setInterval( "doSomething()", iFrequency );  // run
    }
    
    function doSomething()
    {
        // (do something here)
    }
    

    from code...

    <input type="button" onclick="iFrequency+=1000; startLoop(); return false;" 
           value="Add 1 second more to the interval" />
    
    0 讨论(0)
  • 2020-12-15 06:12

    Use

    setInterval

    Calls a function repeatedly, with a fixed time delay between each call to that function.

    for repeated action and

    clearInterval

    Cancels repeated action which was set up using setInterval().

    to stop that

    0 讨论(0)
  • 2020-12-15 06:17

    You could use setTimeout() for this.

    http://www.w3schools.com/htmldom/met_win_settimeout.asp

    0 讨论(0)
  • 2020-12-15 06:19
    <script type="text/javascript">
    var t; var timer_is_on=0; var timeout=5000;
    
    function timedCount() {
      doSomeThing();
      t = setTimeout("timedCount()",timeout);
    }
    
    function doTimer() {
      if (!timer_is_on) {
        timer_is_on=1;
        timedCount();
      }
    }
    
    function stopCount() {
      clearTimeout(t);
      timer_is_on=0;
    }
    function changeFreq() {
       timeout = 2000;
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题