<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 1-2、计时器 -->
<div class="case1">
<button>暂停计时器</button>
</div>
<!-- 3、时针 -->
<div class="case2">
<h1>时针</h1>
</div>
<!-- 4、时间(开始、暂停、结束) -->
<div class="case3">
<h1>时针</h1>
<button class="start">开始</button>
<button class="pause">暂停</button>
<button class="end">结束</button>
</div>
<script>
// 1、setInterval:计时器
var timer = setInterval(() => {
console.log('Hello world!');
}, 2000)
// 2、clearInterval:暂停计时器
var btn = document.querySelector('.case1 button');
btn.onclick = function () {
clearInterval(timer);
}
// 3、计时器显示时针:setInterval
var h1 = document.querySelector('.case2 h1');
setInterval(() => {
let time = new Date();
let hours = time.getHours();
let minutes = time.getMinutes();
let seconds = time.getSeconds();
let timeNow = `${hours}:${minutes}:${seconds}`;
h1.innerHTML = timeNow;
}, 1000);
// 4、时间(开始、暂停、结束)
var timer1 = document.querySelector('.case3 h1');
var start = document.querySelector('.case3 .start');
var pause = document.querySelector('.case3 .pause');
var stop = document.querySelector('.case3 .end');
var seconds = 0;
var ms = 0;
// 显示时间
timer1.innerHTML = `${seconds}:${ms}`;
// 计时器
var timer2 = null;
// 4.1、开始计时器
start.onclick = function () {
// 先清空计时器
clearInterval(timer2);
// 设置计时器
timer2 = setInterval(() => {
if (ms === 9) {
++seconds;
ms = 0;
}
++ms;
timer1.innerHTML = `${seconds}:${ms}`;
}, 100)
}
// 4.2、暂停计时器
pause.onclick = function () {
clearInterval(timer2);
}
// 4.3、结束计时器
stop.onclick = function () {
seconds = 0;
ms = 0;
timer1.innerHTML = `${seconds}:${ms}`;
}
// 5、节流:每隔1秒执行一次(setInterval)
var timer = null;
window.onscroll = function () {
// 先清空计时器,防止计时器叠加
clearInterval(timer);
timer = setInterval(() => {
console.log('节流');
}, 1000);
}
</script>
</body>
</html>