JavaScript的定时器

偶碰到有咨询JavaScript的定时器写出来无法执行的情况,现总理一下,希望能对大家有用。
这里以显示一时钟为例,要求显示现在的时间:
JavaScript定时器的函数是:setInterval(执行的方法,间隔时间);
需要注意的是执行的方法有两种写法:
一是直接用方法体现:


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>title>
head>
<body>
   <p id="clock">p>
   <script type="text/javascript">
       function getDateFormat() {
           var date = new Date();
           var year = date.getFullYear();
           var month = date.getMonth() + 1;
           var day = date.getDate();
           var hour = date.getHours();
           var min = date.getMinutes();
           var second = date.getSeconds();
           var nowTime = year + "/" + month + "/" + day + " " + hour + ":" + min + ":" + second;
           document.getElementById("clock").innerHTML = nowTime;
       }
       setInterval(function(){
           getDateFormat();
       },1000);
   script>
body>
html>

二是用对象变量:


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>title>
head>
<body>
   <p id="clock">p>
   <script type="text/javascript">
       var getDate=function getDateFormat() {
           var date = new Date();
           var year = date.getFullYear();
           var month = date.getMonth() + 1;
           var day = date.getDate();
           var hour = date.getHours();
           var min = date.getMinutes();
           var second = date.getSeconds();
           var nowTime = year + "/" + month + "/" + day + " " + hour + ":" + min + ":" + second;
           document.getElementById("clock").innerHTML = nowTime;
       }
       setInterval(getDate,1000);
   script>
body>

注意不能写成selInterval(getDateFormat(),1000)

你可能感兴趣的:(JavaScript,JavaScript,setInterval)