美文网首页
setTimeout和setInterval的区别

setTimeout和setInterval的区别

作者: jayxiangnan | 来源:发表于2017-04-17 14:09 被阅读0次

    setTimeout()和setInterval()函数的同与异:
    同:都接受两个参数,一个是将要执行的代码块,一个是以毫秒为单位的时间间隔,当过了设定的时间间隔就执行代码块部分。
    异:setTimeout(codeblock, millisec)函数只执行一次代码块,setInterval(codeblock, millisec[,"lang"])函数在执行完一次代码之后,经过固定时间还会自动重复执行代码

        //setInterval()函数以毫秒为单位时间间隔,重复执行代码块
        var showSecond = setInterval("showTime()", 1000);
        function showTime() {
            var date = new Date();
            var seconds = date.getSeconds();
            console.log("the seconds is: " + seconds);  //the seconds is: 
                                                        //the seconds is:
                                                        //the seconds is: 
                                                        //...     
        }
    
        //setTimeout()函数以毫秒为单位时间间隔,执行一次代码块
        var showSecond = setTimeout("showTime()", 1000);
        function showTime() {
            var date = new Date();
            var seconds = date.getSeconds();
            console.log("the seconds is:" + seconds);   //the secons is:
        }
    

    相关文章

      网友评论

          本文标题:setTimeout和setInterval的区别

          本文链接:https://www.haomeiwen.com/subject/wystzttx.html