您的位置:首页 > Web前端 > JavaScript

js通过定时器去显示当前时间及停止

2016-06-12 16:33 441 查看
页面中显示当前时间:

<head lang="en">

    <meta charset="UTF-8">

    <title>通过定时器去显示当前时间</title>

    <script>

        window.onload=function(){

           window.setInterval("showtime()",1000);

        }

        function showtime(){

            var sdom = document.getElementById("spantime");

            var now = new Date();//用来得到当前的时间

            var stime = now.getFullYear()+"年"+(now.getMonth()+1)+"月"

                    +now.getDate()+"日"+now.getHours()+"时"

                    +now.getMinutes()+"分"+now.getSeconds()+"秒";

            sdom.innerHTML= stime;

        }

    </script>

</head>

<body>

   <span id="spantime"></span>

</body>

将定时器停止:

<script>

        var s;

        window.onload=function(){

          s= window.setInterval("showtime()",1000);//表示一个定时器

        }

        function showtime(){

            var sdom = document.getElementById("spantime");

            var now = new Date();//用来得到当前的时间

            var stime = now.getFullYear()+"年"+(now.getMonth()+1)+"月"

                    +now.getDate()+"日"+now.getHours()+"时"

                    +now.getMinutes()+"分"+now.getSeconds()+"秒";

            sdom.innerHTML= stime;

        }

        function stopit(){

            window.clearInterval(s);//停止定时器

        }

    </script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: