前沿: 僅作為筆記記錄,持續(xù)更新
一。首次學習(參考)
- 防抖,防止持續(xù)操作,如點擊事件等
原理:固定時間只能操作一次
思路:每次點擊的時候讓它把之前的定時器清空,最終只執(zhí)行當前的操作。 - 節(jié)流,防止持續(xù)輸出,如鼠標移動事件持續(xù)移動、瀏覽器窗口變化持續(xù)打印等
原理:固定時間只會輸出一次
思路:每幾秒時候再執(zhí)行,最終一定時間只會執(zhí)行一次。
<!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>