JS Date对象的方法简介

setInterval:循环执行。window.setInterval("方法名或方法","时间间隔"); 重复执行

setTimeout:定时执行。window.setTimeout("方法名或方法","延时"); 执行一次

html页面

<strong id="date"></strong>

js setInterval代码

    <script type="text/javascript">
        window.onload = function () {
           //循环执行
           window.setInterval(show, 1000);            
        }
        function show() {
            var $now = new Date();
           //获取年月日时分秒
            var $dt = $now.getFullYear() + "-"
                      + ($now.getMonth() < 10 ? "0" : "") + ($now.getMonth() + 1) + "-"
                      + ($now.getDate() < 10 ? "0" : "") + $now.getDate() + " "
                      + ($now.getHours() < 10 ? "0" : "") + $now.getHours() + ":"
                      + ($now.getMinutes() < 10 ? "0" : "") + $now.getMinutes() + ":"
                      + ($now.getSeconds() < 10 ? "0" : "") + $now.getSeconds();
            $("#date").text($dt);
        }
    </script>

setInterval()效果重复执行,时间不断变动。

js setTimeout代码

    <script type="text/javascript">
        window.onload = function () {
           //只执行一次
           window.setTimeout(show, 3000);    
        }
        function show() {
            var $now = new Date();
            //获取年月日时分秒
            var $dt = $now.getFullYear() + "-"
                      + ($now.getMonth() < 10 ? "0" : "") + ($now.getMonth() + 1) + "-"
                      + ($now.getDate() < 10 ? "0" : "") + $now.getDate() + " "
                      + ($now.getHours() < 10 ? "0" : "") + $now.getHours() + ":"
                      + ($now.getMinutes() < 10 ? "0" : "") + $now.getMinutes() + ":"
                      + ($now.getSeconds() < 10 ? "0" : "") + $now.getSeconds();
            $("#date").text($dt);
        }
    </script>

setTimeout()效果执行一次,时间不再变动。

取消操作

var intervalId=window.setInterval("方法名或方法","时间间隔");
window.clearInterval(intervalId);

var timeoutId=window.setTimeout("方法名或方法","延时");
window.clearTimeout(timeoutId);

 

 posted on 2019-06-19 15:22  会飞的金鱼  阅读(116)  评论(0编辑  收藏  举报