There are times when I want to fire a method once an amount of time has passed. I can always just use setTimeout or setInterval, and make my own solution that is some kind of advanced process management solution. However this is a lodash post as such I shale be writing some _.throttle examples, which is one way to make throttled methods.
So here are some quick examples.
_.throttle differers from setTimeout and setInterval as it returns a new function that will only fire once the amount of time has passed when it is being called, rather than setting a function to call after an amount of time has passed, or at a certain interval.
_.throttle is a good example of what can be done with closures, and high order functions. Which are just fancy terms for functions within functions that accept functions as one or more of there arguments.
I was able to put this together in a flash. I love quick little examples like this, and also If I wanted to I could go in a novel, custom direction with it.
What is returned is an api that uses the method that is given to it as the first argument. This way whenever I call the method that is returned I am not directly calling the given method, I am instead calling a method inside the body of my throttle method that will call the given method when a given amount of time has passed.
I also have the beginning of a more complex api starting in which I can also just directly call the given method if I want to with a properly named “now” method.