防抖節流的區別 怎麼實現防抖節流
阿新 • • 發佈:2022-11-29
防抖節流區別 怎麼實現的
防抖:指在觸發事件後n秒內函式只執行一次(確定不在更改時執行) 如果在n秒內再次被觸發則時間會被重新計算 如:王者裡面的回城 如果回城終端 則會重新計算回城時間
使用什麼實現:使用閉包實現 或者lodash(使用時引入js外掛)_.throttle(func函式, [wait=0等待時間], [options=這個引數可有可無])
節流:在既定時間內連續多次觸發事件時 不會重新計算時間 而是將本次執行的時間 執行完成後才會再次被觸發 如:簡訊驗證碼倒計時 在驗證碼出發後再點選也是無效的 倒計時時間不會被重新計算 而是等在既定的時間內執行完後才能再次被觸發
使用什麼實現:使用閉包 或者loadsh外掛_.debounce(func, [wait=0], [options=])
防抖節流區別:防抖在既定時間內 再次被觸發後重新計算時間 再執行 而節流連續觸發不會重新計算時間 只有既定時間結束後才會被再次觸發事件
節流:在既定時間內連續多次觸發事件時 不會重新計算時間 而是將本次執行的時間 執行完成後才會再次被觸發 如:簡訊驗證碼倒計時 在驗證碼出發後再點選也是無效的 倒計時時間不會被重新計算 而是等在既定的時間內執行完後才能再次被觸發
防抖節流區別:防抖在既定時間內 再次被觸發後重新計算時間 再執行 而節流連續觸發不會重新計算時間 只有既定時間結束後才會被再次觸發事件
<title>Document</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text -align: center;
font-size: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
使用閉包來實現節流
// 節流:連續觸發事件 但在設定時間內只會執行一次(如:簡訊驗證碼)
// 防抖:指在觸發事件在n秒內只執行一次 如果在n秒內再次出發 則會重新計算時間(如:王者中的回城)
let i = 0;
const box = document.querySelector(".box");
function renderMove() {
box.innerHTML = i++;
}
// 沒有節流時 動一下就會改變一下數字 開啟節流閥後 在1秒後才會觸發一次
box.addEventListener("mousemove", throttle(renderMove, 1000));
// 節流 0-2 時間內會加1 (約定一個時間範圍只會執行一次)
function throttle(fn, time) {
let start = 0;
function fun() {
let now = +new Date();
if (now - start >= time) {
// 重新呼叫函式
fn();
start = now;
console.log(start);
}
}
return fun;
}
console.log(throttle(renderMove, 1000));
</script>
</body>
<title>Document</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
使用閉包實現防抖
const box = document.querySelector(".box");
let i = 0;
// 渲染函式 將事件函式裡面的函式抽離出來
function render() {
box.innerHTML = i++;
}
box.addEventListener("mousemove", antiShake(render, 200));
function antiShake(fn, time) {
let timeId; //undefined 定時器的名字
return function () {
if (timeId) {
// 清除之前的定時器 重新經計時
clearTimeout(timeId);
}
//定時器
timeId = setTimeout(function () {
fn();
}, time);
};
}
</script>
</body>
<title>Document</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<!-- 引入js外掛 -->
<script src="./lodash.min.js"></script>
<script>
使用lodas外掛來實現防抖節流
const box = document.querySelector(".box");
let i = 0;
function mouseMove() {
box.innerHTML = ++i;
}
// 防抖 _.debounce(func, [wait=0], [options=])
// box.addEventListener("mousemove", _.debounce(mouseMove, 500));
// 節流_.throttle(func, [wait=0], [options=])
box.addEventListener("mousemove", _.throttle(mouseMove, 1000));
</script>
</body>