Home >Web Front-end >JS Tutorial >## Why Do JavaScript Throttle Functions Sometimes Fire Once More After the Throttle Time Has Elapsed?
JavaScript throttling is a useful technique that can prevent functions from being executed too frequently. This can be particularly beneficial in situations where excessive function calls can cause performance issues or unintended effects.
The following JavaScript code provides a reusable "throttle" function:
<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); } }; }
However, the provided function has a notable drawback. After the throttle time has elapsed, it fires the function one more time. This can lead to undesired behavior in certain scenarios.
A revised version of the throttling function is available from libraries such as underscore.js and lodash. This version effectively addresses the issue of firing the function after the throttle time:
<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>
A simplified, non-configurable version of the throttling function is provided below:
<code class="javascript">function throttle (callback, limit) { var waiting = false; // Initially, we're not waiting return function () { // We return a throttled function if (!waiting) { // If we're not waiting callback.apply(this, arguments); // Execute users function waiting = true; // Prevent future invocations setTimeout(function () { // After a period of time waiting = false; // And allow future invocations }, limit); } } }</code>
With this function, you can control the frequency of function executions by adjusting the "limit" parameter.
The above is the detailed content of ## Why Do JavaScript Throttle Functions Sometimes Fire Once More After the Throttle Time Has Elapsed?. For more information, please follow other related articles on the PHP Chinese website!