Throttle a function with leading and trailing call options
This problem extends the concept of throttling function executions, introducing an improved version of the throttle() function. The enhanced throttle() function now accepts an additional third parameter: an options object. This object includes two boolean properties: leading and trailing. The leading property decides if the throttled function should be invoked at the start or after a delay, while the trailing property controls whether the function should be called after the delay concludes or right away. CSS-Tricks explains the difference between debouncing and throttling.
The primary objective is to design a throttling function that can limit the execution rate of a given function. Unlike the basic implementation from the previous problem, this version grants more control over the throttled function’s behavior, allowing for a more tailored functionality.
To illustrate, consider the following examples which demonstrate how the options object influences the throttling:
{ leading: true, trailing: false }, the function will execute immediately on the first call, then ignore all calls during the wait time.{ leading: false, trailing: true }, the function will ignore the initial call, then execute at the end of the wait time, applying the last arguments passed during the wait.To verify the correctness of your throttle() function, a test function named run() is provided. It simulates function calls, capturing their timing, and utilizes setTimeout() to manage execution based on the specified delay and options. The outcome is an array of strings that represent the executed function calls and their respective timings.
Given this setup, your task is to implement the improved throttle() function. Ensure that it adheres to the specified behavior, taking into account the leading and trailing options, and that it functions accurately even in the complex browser environment where setTimeout() and clearTimeout() might not always be precise.