1747306304
2025-05-15 10:48:00
スロットリングは、JavaScriptのユーザーインタラクションの最適化手法です。
これは、関数が実行されるレートを制御するために使用される手法です。複数回トリガーされたとしても、指定された時間間隔で関数がせいぜい1回呼び出されることが保証されます。
関数がyミリ秒間スロットされると、それはそのyミリ秒でせいぜい一度に呼び出されるか、yミリ秒ごとにせいぜい1回しか呼び出されないことを意味します。
スロットリングをいつ使用するのですか?
スロットリングは、イベントが頻繁に解雇されるシナリオで役立ちます。イベントにはタイプがあります。
- ウィンドウサイズ変更
- イベントをスクロールします
- マウスの動き
- ボタンクリック(複数の提出を防ぐため)
スロットリングの基本的な実装
スロットリングの基本的な実装をしましょう。それを行う前に、最初に要件をリストして、それに基づいて実装を書き出すことができます。
- イベントの最初の発生時に実行されます
- その後、指定された量の遅延の後、イベントが再び起動された場合に実行され、それまで実行がブロックされます。
- スロットリングは私たちにスロットルされた機能を与えることを忘れないでください
これは、遅延中のイベントを無視する基本的な実装です。
function throttle(functionToBePassed , delay){
// to keep track if the event has occured or not yet
let startId = null;
// recieve the arguements
return function(...args){
// if the event hasnt occured yet
if(!startId){
// invoke the function
functionToBePassed(...args);// a startId get assigned and remains until the delay has passed
startId = setTimeOut(() =>{
// as soon as the timer ends make the startId null
startId = null;
},delay);
}
}
}
遅延中に解雇された最後のイベントを実行したいとしましょう。
function throttle(functionToBePassed, delay) {
let startId = null;
let lastArgs = null;return function (...args) {
// if the event hasnt occured yet
if (!startId) {
// invoke the function
functionToBePassed(...args);
startId = setTimeout(() => {
if (lastArgs) {
functionToBePassed(...lastArgs);
lastArgs = null; // Reset lastArgs after execution
}
startId = null; // Reset startId so the function can run again
}, delay);
} else {
lastArgs = args; // Store the latest arguments
}
};
}
次に、いくつかの高度なスロットリングケースをさらに深く掘り下げましょう。
- 主要なケース
- トレーリングケース
Leading case:
主要なケースを備えたスロットルがあるとしましょう。その後、関数はイベントが発生したときにすぐに呼び出され、スロットル期間中のその後のイベントは無視されます。
Trailing Case :
トレーリングにより、スロットル期間の終わりに関数がイベントの最後のデータを使用して実行されることが保証されます。
コードでそれを見てみましょう:
function throttle(fn, delay, option = { leading: true, trailing: true }) {
const { leading, trailing } = option;
let lastTimerId;
let lastArgs;return function (...args) {
const waitFn = () => {
if (trailing && lastArgs) {
fn.apply(this, lastArgs); // or fn(...args);
lastArgs = null; // reset lastArgs
lastTimerId = setTimeout(waitFn, delay); // executes the
} else {
lastTimerId = null;
}
};
// case : leading case
if (!lastTimerId && leading) {
// call immediately
fn.apply(this, args);
} else {
// storing the last arguments for the trailing case
lastArgs = args;
}
// case : trailing case
if (!lastTimerId) {
lastTimerId = setTimeout(waitFn, delay);
}
};
}
これはすべてスロットリングについてでした。読んでくれてありがとう!
#JavaScriptインタビューパート2JSのスロットリングとは何ですか #Pratik #Rai #2025年5月