1、setInterval与clearInervar
实现秒表功能
<button class="start">开始</button>
<button class="stop">暂停</button>
<button class="end">结束</button>
<h1 class="time">10:9</h1>
<script>
let start = document.querySelector('.start')
let stop = document.querySelector('.stop')
let end = document.querySelector('.end')
let time = document.querySelector('.time')
let seconds = 0
let ms = 0
time.innerHTML = `${seconds}:${ms}`
let timer = null
// 开启计时器
start.onclick = function () {
// 开始的时候删掉之前的计时器并重新开启一个计时器 防止多次开启计时器越来越快的情况
clearInterval(timer)
timer = setInterval(() => {
// 设置进制
if (ms === 9) {
seconds++
ms = 0
}
ms++
time.innerHTML = `${seconds}:${ms}`
}, 100)
}
// 暂停计时器
stop.onclick = function () {
clearInterval(timer)
}
// 结束计时器
end.onclick = function () {
seconds = 0
ms = 0
time.innerHTML = `${seconds}:${ms}`
}
</script>
2、setTimeout与clearTimeout
<button>停止</button>
<script>
let timer = null
// 设置两秒后触发
timer = setTimeout(() => {
console.log('hello world')
}, 2000)
// 终止触发
document.querySelector('button').onclick = function () {
clearTimeout(timer)
}
</script>
// 延时跳转
<body>
<h1>5秒后跳转到百度</h1>
<script>
setTimeout(() => {
location.href = "http://www.baidu.com"
}, 5000)
</script>
</body>
防抖与节流
解决性能问题,开发中经常遇到
防抖:对于短时间内多次触发事件的情况,可以使用防抖停止事件持续触发(当行为停止后触发)
<!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>
<style>
body {
height: 2000px;
}
</style>
</head>
<body>
<h1>window.onscroll事件</h1>
<script>
// 防抖
let timer = null
window.onscroll = function () {
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(() => {
console.log('hello world')
timer = null
}, 500)
}
</script>
</body>
</html>
节流:防止短时间内多次触发事件的情况,但是间隔事件内,还需要不断触发(在行为过程中隔一段时间触发)
// 节流
let mark = true // 标记
window.onscroll = function () {
if (mark) {
setTimeout(() => {
console.log('hello world')
mark = true
}, 500)
}
mark = false
}
返回顶部效果
1、window.onscroll事件 ;滚动条滚动事件
2、document.documentElement.scrollTop:页面滚动位置距离顶部位置
3、window.scrollTo(0,0):让页面滚动条返回至顶部
练习
1、在网页中显示当前时间
2、在网页中制作一个秒表
3、实现一个五秒后跳转页面的效果
4、返回顶部(防抖)
5、返回顶部(节流)