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

前端 未结 4 1772
佛祖请我去吃肉
佛祖请我去吃肉 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...

    
    

提交回复
热议问题