代码之家  ›  专栏  ›  技术社区  ›  steven

每5秒做一次,然后用代码停止。(jQuery)

  •  21
  • steven  · 技术社区  · 16 年前

    我怎样才能重复一个函数 doSomething() 每5秒。

    我还需要一些代码来让它停止工作。

    并对编码进行实时调整频率。

    4 回复  |  直到 10 年前
        1
  •  34
  •   pixeline    16 年前

    setTimeout()将只启动一次命令。在本例中,setInterval()是您的朋友。

    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)
    }
    

    从代码…

    <input type="button" onclick="iFrequency+=1000; startLoop(); return false;" 
           value="Add 1 second more to the interval" />
    
        2
  •  7
  •   rahul    16 年前

    使用

    setInterval

    重复调用函数,使用 每次呼叫之间的固定时间延迟 那个函数。

    重复动作和

    clearInterval

    取消已设置的重复操作 使用setInterval()启动。

    停止

        3
  •  0
  •   svens    16 年前
        4
  •  0
  •   jitter    16 年前
    <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>