
Member-only story
Throttling and Debouncing in JavaScript
Are you excessively invoking functions and hampering performance?
Tackling performance often crops up in JavaScript applications.
Throttling and debouncing give us control over the rate at which a function is called. They are need to know techniques for any web developer. They are especially useful when we are dealing with event handler assignments. There are scenarios where we may invoke functions when it isn’t necessary. Consider a callback that we want to execute on window resize. Does it make sense to fire the callback as we resize? Most likely not. We want to wait til the user has finished interaction and then fire the callback.
For those in camp TL;DR, here’s a demo!
What’s the difference between throttling and debouncing?
- Throttling — If you think of a car throttle. The amount you push your foot down limits the amount of gas going into the engine. In this context, we want to limit the amount a function is invoked. I find a better analogy to be either the lottery, only one ball is drawn every five seconds. Or a better analogy being ordering drinks at a bar. You go to a bar and the barman has a policy of only allowing you to order a drink every 45 minutes (Or things get crazy). You order a drink in the first minute and they hand one over. You then try and order one every minute after. The barman denies you until the 45th minute when the then tired barman hands over the next drink. You won’t get another drink for another 45 minutes. With throttling, you may want one last invocation to happen after the throttle is over. This will be one of the denied invocations. Imagine you order a drink in the 15th minute and get denied. In the 45th minute, you don’t order but the barman sends a waiter over with the drink from that 15th minute order. They feel sorry for you 😁
- Debouncing—Debouncing works a little different. It can be a little harder to explain. With debouncing, it’s like “Hey, I’m not…