简单的javascript实例一(时钟特效)

方便以后copy

时钟特效

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>时钟特效</title>
<script type="text/javascript">
    function time(){
        var today = new Date(); //得到当前时间
        //获得年、月、日、小时、分钟、秒
        var yy = today.getFullYear();
        var MM = today.getMonth();
        var dd = today.getDay();
        var hh = today.getHours();
        var mm = today.getMinutes();
        var ss = today.getSeconds();
        
        document.getElementById("time").innerHTML="<h1>"+yy+""+MM+""+dd+""+hh+":"+mm+":"+ss+"</h1>";
        //每秒钟回调一次
        setTimeout(time,1000);
    }
</script>
</head>
<body onload="time()">
    <div id="time"></div>
</body>
</html>

JavaScript中提供了两个定时器函数:setTimeout()和setInterval()。

setTimeout()用于在指定的毫秒后调用函数或计算表达式。语法格式如下:

setTimeout(调用的函数名称,等待的毫秒数)    如:

setTimeout(time,1000);

可以使用clearTimeout()清除定时器,如:

var t = setTimeout(time,1000);
clearTimeout(t);//清除定时器

setInterval()可按照指定的周期(以毫秒计)来调用函数或计算表达式。语法格式如下:

setInterval(调用的函数名称,周期性调用函数之间间隔的毫秒数)   如:

setInterval(time,1000);

可以使用clearInterval()清除定时器,如:

var t = setInterval(time,1000);
clearInterval(t);//清除定时器

setTimeout()只执行一次,如果要多次调用函数,需要使用setInterval()或者让被调用的函数再次调用setTimeout()。

原文地址:https://www.cnblogs.com/likailan/p/3381717.html