setTimeout or setInterval?

前端 未结 19 3158
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:59

As far as I can tell, these two pieces of javascript behave the same way:

Option A:

function myTimeoutFunction()
{
    doStuff();
           


        
19条回答
  •  爱一瞬间的悲伤
    2020-11-21 05:27

    setInterval()

    setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

    If you want to loop code for animations or on a clock tick, then use setInterval().

    function doStuff() {
        alert("run your code here when time interval is reached");
    }
    var myTimer = setInterval(doStuff, 5000);
    

    setTimeout()

    setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless you gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

    function doStuff() {
        alert("run your code here when time interval is reached");
    }
    var myTimer = setTimeout(doStuff, 5000);
    

    If you want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.

提交回复
热议问题