前沿: 仅作为笔记记录,持续更新
一。首次学习(参考)
- 防抖,防止持续操作,如点击事件等
原理:固定时间只能操作一次
思路:每次点击的时候让它把之前的定时器清空,最终只执行当前的操作。 - 节流,防止持续输出,如鼠标移动事件持续移动、浏览器窗口变化持续打印等
原理:固定时间只会输出一次
思路:每几秒时候再执行,最终一定时间只会执行一次。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<button id="debounce">debounce</button>
<button id="throttle">throttle</button>
</div>
</body>
</html>
<script>
const debounce = (fn, delay) => {
let timer = null
return function(){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(fn, delay)
}
}
const throttle = (fn, delay) => {
let flag = true
return function (){
if(!flag){
return false
}
flag = false
setTimeout(() => {
flag = true
fn()
},delay)
}
}
const deDothing = () => {
console.log('debounce')
}
const thDothing = () => {
console.log('throttle')
}
const debounceDom = document.getElementById('debounce')
debounceDom.onclick = debounce(deDothing, 1000)
const throttleDom = document.getElementById('throttle')
throttleDom.onclick = throttle(thDothing, 1000)
</script>