ホームページ > 記事 > ウェブフロントエンド > 記事の内容に適した質問ベースのタイトルをいくつか示します。 * **JavaScript で単純なスロットリングを実装するにはどうすればよいですか?** * **JavaScript 関数を調整する最良の方法は何ですか?** *
JavaScript での単純なスロットリング
JavaScript におけるスロットリングは、関数の実行を特定の時間間隔に制限する手法です。これは、過剰な関数呼び出しによるシステムの過大な負荷を回避したい場合に便利です。
既存のスロットル実装
lodash や underscore などのライブラリは、組み込みのスロットル関数を提供します。ただし、単純なタスクにこれらのライブラリ全体を含めるのは冗長になる可能性があります。
カスタム スロットル関数
スタンドアロン ソリューションとして使用できるカスタム スロットル関数を次に示します。
<code class="javascript">function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last, deferTimer; return function () { var context = scope || this; var now = +new Date, args = arguments; if (last && now < last + threshhold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } }; }
改善: 重複実行の回避
ただし、提供されたコードでは、スロットル間隔が経過すると関数が再度起動される可能性があるという問題が発生します。これに対処するには、次のように関数を変更します。
<code class="javascript">function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last, deferTimer; return function () { var context = scope || this; var now = +new Date; if (now < last + threshhold) { return; // prevent subsequent execution } last = now; fn.apply(context, arguments); }; }
Advanced Throttle Function
柔軟性と追加オプションについては、次の実装を参照してください。 :
<code class="javascript">function throttle(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; };</code>
以上が記事の内容に適した質問ベースのタイトルをいくつか示します。 * **JavaScript で単純なスロットリングを実装するにはどうすればよいですか?** * **JavaScript 関数を調整する最良の方法は何ですか?** *の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。