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); }; }
進階節流函數
為了獲得更多的靈活性和更多選項,您可以參考以下實作:
<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中文網其他相關文章!