setTimeout 与setInterval的区别

setTimeout(code,millisec) 方法用于在指定的毫秒数后调用函数或计算表达式

setInterval(code,millisec) 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式

区别:setTimeout() 只执行 code 一次。如果要多次调用,请使用 setInterval() 或者让 code 自身再次调用 setTimeout()

 

setTimeout() 函数实现时钟的例子

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>预备启动秒表</title>
    <script type="text/javascript">
        function timedMsg()
        {
            var second = document.getElementById("second").value;
            var minute = document.getElementById("minute").value;
            var hour = document.getElementById("hour").value;

            second = parseInt(second);
            minute = parseInt(minute);
            hour = parseInt(hour);
var second = second + 1; if(second >59){ second = 0; minute = minute + 1; if(minute > 59){ minute = 0; hour = hour + 1; if(hour>23){ hour = 0; } } } //数据格式处理 if(second < 10){ second = "0" + second; } if(minute < 10){ minute = "0" + minute; } if(hour < 10){ hour = "0" + hour; } document.getElementById('second').value= second; document.getElementById('minute').value= minute; document.getElementById('hour').value= hour; var t = setTimeout("timedMsg();",1000); } </script> </head> <body> <button onclick="timedMsg()">预备启动秒表</button> <br> <br><input type="text" name="hour" id="hour" value="00"><input type="text" name="minute" id="minute" value="00"><input type="text" name="second" id="second" value="00"> </body> </html>

 

posted @ 2018-03-16 11:42  坚持奔跑在路上  阅读(209)  评论(0编辑  收藏  举报