1.Date对象基本使用
<script>
// 1. 声明日期对象
var date = new Date();
// console.log(date);
console.log(date.getDate()); // 日
console.log(date.getDay()); // 星期几
console.log(date.getMonth() + 1); // 月
console.log(date.getFullYear() ); // 完整的年份
console.log(date.getHours() ); // 小时
console.log(date.getMinutes() ); // 分钟
console.log(date.getSeconds() ); // 秒
console.log(date.getMilliseconds() ); // 毫秒
console.log(date.getTime() ); // 时间戳
</script>
2.定时器操作
创建以及清除定时器:
<script>
window.onload = function () {
// 1.获取需要的标签
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var height = 150, timer = null;
// 2. 开启定时器
btn1.onclick = function () {
// 2.1 设置定时器
timer = setInterval(function () {
height += 1;
console.log("身高是" + height + "cm");
}, 1000);
};
// 3. 结束定时器
btn2.onclick = function () {
console.log(timer);
clearInterval(timer);
}
}
</script>
但是这种写法可能会出现问题,那就是可能会出现定时器叠加的后果,所以,我们一般都是先清除定时器,再设置定时器。
自定义时间:
<script>
// 1. 自定义现在的时间
var currentDate = new Date();
console.log(currentDate);
var nextDate = new Date('2018/08/08 08:17:35');
console.log(nextDate);
var preDate = new Date('2017/08/08 08:17:35');
console.log(preDate);
</script>
一次定时器:
<script>
window.onload = function () {
// 1. 获取需要的标签
var btn = document.getElementById("btn");
var btn1 = document.getElementById("btn1");
var timer = null;
// 2. 监听按钮的点击
btn.onclick = function () {
clearTimeout(timer);
// 一次定时器
timer = setTimeout(function () {
alert('请你去吃饭');
}, 3000);
};
btn1.onclick = function () {
clearTimeout(timer);
}
}
</script>