节流在触发后,在该时间段内无论触发多少次都无效,只有过了这段时间才能继续触发,类似于王者的技能冷却
<!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>
<button id="btn">+1</button>
<script>
// 默认是立即执行
function throttle(fn, interval, immediate = true) {
// 1.定义变量保记录开始时间
let startTime = 0
const _throttle = function (...args) {
// 2. 获取当前时间
const nowTime = new Date().getTime()
if (!immediate && startTime === 0) {
startTime = nowTime
}
// 3.计算需要等待的时间
const waitTime = interval - (nowTime - startTime)
// 4.当等待的时间小于等于0时, 执行回调函数
if (waitTime <= 0) {
fn.apply(this, args)
// 并让开始时间等于现在时间
startTime = nowTime
}
}
return _throttle
}
let counter = 0
const btn = document.querySelector('#btn')
function add() {
console.log(`打印了${++counter}次`, this)
}
btn.onclick = throttle(add, 2000)
</script>
</body>
</html>