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中文网其他相关文章!