概念
Date对象基于1970年1月1日(世界标准时间)起的毫秒数
定时器
需求:
1、JS程序的执行速度是费差个快的,如果希望一段程序,可以每隔可一段时间执行一次,可以使用定时调用
2、某一程序需要在延迟多少时间后执行,可以使用定时器调用
定时器的循环执行
<script>
// 循环执行 定时器
//每一秒执行一次 1000是毫秒
//法一
setInterval(function(){
console.log('aaa');
},1000);
//法二
setInterval(" console.log('aaa');",1000);
//法三
function fun (){
console.log('aaa');
}
setInterval(fun,1000); //不要加小括号,传过来的是一个函数对象
</script>
这里注意一下setInterval中的函数不加小括号
区别:
function fun (){
console.log('aaa');
}
// setInterval(fun,1000); //不要加小括号,传过来的是一个函数对象
console.log(fun);
console.log(fun()); //加小括号传过来的是结果,这里是undefined
Date常用方法一
<!-- 3 Data常用方法 -->
<script>
//过去时间
var date2 = new Date('2000/3/15 08:08:08');
console.log(date2);
//当前时间
var date = new Date();
console.log(date);
//将来事件
var date1 = new Date('2020/3/15 08:08:08');
console.log(date1);
</script>
Date常用方法二
<script>
var date = new Date();
console.log(date.getTime()); //返回一个毫秒数 距离1970.1.1
console.log(date.getMilliseconds()); //返回毫秒 0-1000
console.log(date.getSeconds()); //返回0-59
console.log(date.getMinutes()); //返回0-59
console.log(date.getHours()); //返回0-23
console.log(date.getDay()); //返回星期几 0周日 6周六
console.log(date.getDate()); //返回当前月的第几天
console.log(date.getMonth()); //返回月份 从零开始
console.log(date.getFullYear()); //返回四位的月份 如:2020
</script>
Date格式转化的实现
可以将这个封装,以备日后使用
<script>
//写一个函数,格式化日期对象 返回YYYY-MM--DD hh:mm:ss的形式
var d = fromat(new Date());
console.log(new Date());
console.log(d);
//格式化函数
function fromat(date) {
//验证
if( !date instanceof Date) {
return ;
}
//转化
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
//转化格式
month = month < 10? '0' + month:month;
day = day < 10? '0' + day:day;
hour = hour < 10? '0' + hour:hour;
minute = minute < 10? '0' +minute :minute ;
second = second < 10? '0' + second:second;
return year +'-' + month + '-' + day + ' ' + hour + ':' + minute + ':' +second;
}
</script>
表白神器
案例描述
浏览器上五秒倒计时,时间到后可以显示图片或者是任何想说的话或者一个视频等等(我在这里就简单地展示一下,后续你们阔以自由发挥啦)
代码如下,关键步骤注释中都有解释
效果展示
1、倒计时
2、图片展示
HTML+CSS
<style>
*{
margin: 0;
padding: 0;
}
body {
background-color: #000;
text-align: center;
padding: 200px;
}
#pic {
display: none;
}
img {
width: 200px;
}
#time {
font-size: 100px;
color: red;
}
</style>
<body>
//表白神器
<div id='time'>5</div>
<img id="pic" src="./program1/images/1.jpg" alt="">
</body>
JS核心代码
<script>
window.onload = function() {
var inter = setInterval(function(){
$("time").innerHTML -= 1;
//清除定时器
if( $("time").innerHTML == 0) {
clearInterval(inter);
// 显示图片和隐藏时间
$("time").style.display = 'none';
$("pic").style.display = 'block';
}
},1000)
}
//封装
function $(id) {
return typeof id === 'string' ? document.getElementById(id):null;
}
</script>