コンセプト:
- アンチシェイク: イベントがトリガーされてから n 秒後にコールバックを実行します。イベントが n 秒以内に再度トリガーされると、タイミングが再開されます。
- スロットリング: 指定された時間内でイベントをトリガーできるコールバックは 1 つだけであり、単位時間内に繰り返しトリガーされた場合は効果がありません。
アプリケーションシナリオ:
- 手ぶれ補正: 入力ボックス入力 (入力)...
- スロットル: ブラウザ ウィンドウの変更 (サイズ変更)、ページのスクロール (スクロール)、ドラッグ (ドラッグ)...
安定:
function debounce(fn, delay) {
let timer = null;
return function () {
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay)
}
}
* * スロットル:
function throttle(fn, delay) {
let timer = null;
return function () {
if(timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay)
}
}
移行:
const btn = document.querySelector('button')
btn.addEventListener('click', debounce(function () {
console.log('发财小手点个关注')
}, 1000, true))