Namespace: Functions:throttle

Functions:throttle

Methods

throttle(ms, func, hasLeadingExecutionopt, nullable, hasTrailingExecutionopt, nullable) → {function}

Returns a throttled function (based on an unthrottled one), which executes only once in a timeframe at most. This is especially helpful to react to events, that might come in avalanches in an orderly and performant way, let's say changing layout due to a resizing or scrolling event.

If you are trying to react to events, that occur a lot, in a synchronous fashion, meaning, that you rely on values and data having been updated after the event, so there is a clear time arrow of things happening in order, you might need to set hasLeadingExecution and/or hasTrailingExecution to true to better cover those cases.

Be aware that the precision of this method relies in part on the client's cpu, so this is implementation might not be right if you need a razor sharp exact amount of calls in a given time every time, this is a more simple and fuzzy implementation for basic purposes, which should cover 90% of your needs. For a more precise and battle-tested version, see lodash's complex implementation: https://www.npmjs.com/package/lodash.throttle

Parameters:
Name Type Attributes Default Description
ms Number

the timeframe for one execution at most in milliseconds

func function

the function to throttle

hasLeadingExecution Boolean <optional>
<nullable>
false

defines that the function call that starts a timeframe, does not count, so that during the following frame another call is possible

hasTrailingExecution Boolean <optional>
<nullable>
false

defines if the function is executed at the end of the timeframe (will only happen, if there were more than one calls to the function in the time frame)

Source:
Throws:

error if ms is no number > 0 or func is not a function

Returns:
the throttling function (parameters will be handed as is to the throttled function)
Type
function
Example
window.addEventListener('resize', throttle(400, function(){ console.log(`the viewport is now ${window.innerWidth}px wide`); }));