JavaScript timers and cases
Two useful timing methods
- window.setTimeout(call function,[delayed milliseconds]);
window can be omitted when calling the
delay milliseconds can be omitted, the default value is called after 0 milliseconds. The
calling function can be written on the external
page. There are usually many timers. We will assign the timer to the variable
window.addEventListener('load', function() {
var time = setTimeout(fn, 1000);
function fn() {
console.log('这是一个定时器');
}
clearTimeout(time); //清除定时器
})
Another way of writing
window.addEventListener('load', function() {
setTimeout(function() {
alert('爆炸了');
}, 5000);
})
Another way of writing
window.addEventListener('load', function() {
setTimeout('fn()', 5000);
function fn() {
alert('这是一个定时器');
}
}) //不提倡这种写法
Stop the timer window.clearTimeout()
- window.setInterval(call function,[delayed milliseconds]);
window can be omitted when calling the
delay milliseconds can be omitted, the default value is called after 0 milliseconds. The
calling function can be written in the external
page. There are usually many timers. We will assign
a timer to a variable, call a function repeatedly, and execute the same code every once in a while
window.addEventListener('load', function() {
setInterval(function() {
console.log('hh');
}, 1000);
})
Stop the timer window.clearInterval()
Case: How long is it until 00:00:00 on December 30, 2020?
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 550px;
margin: 100px auto;
}
span {
display: inline-block;
width: 70px;
height: 70px;
background-color: black;
color: white;
text-align: center;
line-height: 70px;
font-size: 18px;
}
</style>
</head>
<body>
<div class="box">距离2020年12月30日00:00:00还有
<span class="day">天</span>
<span class="hour">小时</span>
<span class="minute">分钟</span>
<span class="second">秒</span>
</div>
<script>
window.addEventListener('load', function() {
var day = document.querySelector('.day');
var hour = document.querySelector('.hour');
var minute = document.querySelector('.minute');
var second = document.querySelector('.second');
var future = +new Date('2020-12-30 00:00:00'); //得到'2020-12-30 00:00:00'的时间戳
getTime(); //首先调用函数,防止页面刚加载时空白
function getTime() {
var now = +new Date(); //得到现在的时间戳
var ms = (future - now) / 1000; //得到现在距'2020-12-30 00:00:00'的总秒数
var Day = parseInt(ms / 60 / 60 / 24); //得到天数
var Hour = parseInt(ms / 60 / 60 % 24); //得到小时数
var Minute = parseInt(ms / 60 % 60); //得到分钟数
var Second = parseInt(ms % 60); //得到秒数
day.innerHTML = Day + '天';
hour.innerHTML = Hour + '时';
minute.innerHTML = Minute + '分';
second.innerHTML = Second + '秒';
}
var countDown = setInterval(getTime, 1000); //每隔一秒调用一次定时器
})
</script>
</body>